Skip to content

MERN Stack Interview Questions in Chandigarh

36 practice questions with answers for MERN Stack interviews in Chandigarh.

MERN Stack jobs in Chandigarh

Chandigarh, Mohali and Panchkula form the Tricity IT cluster, with IT-services firms, SaaS companies and start-ups in Mohali's IT City and Chandigarh's IT Park. Interviews usually check strong fundamentals and practical tool skills.

Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Chandigarh.

Solved for ChandigarhStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Your app needs user, editor and admin roles with different permissions. How would you implement it?

Save to ▾
Show answer
Store a role, or a list of permissions, on the user document and include it in the token or load it in the auth middleware. Write an authorize middleware that checks allowed roles or permissions per route, for example authorize('admin'). Add ownership checks in services, such as an editor editing only their own articles. In React, hide buttons by role for user experience, but always enforce rules on the server.
02

How does React protect against XSS and where can XSS still happen?

Save to ▾
Show answer
React escapes values rendered in JSX, so user text containing script tags is shown as text, not executed. XSS can still happen through dangerouslySetInnerHTML with unsanitised HTML, javascript: URLs in href attributes, injecting user data into script tags during SSR, or unsafe third-party scripts. Sanitise any HTML with DOMPurify, validate URLs, set a Content Security Policy, and keep tokens out of JavaScript-readable storage.
03

Write a central error-handling middleware with a custom AppError class.

Save to ▾
Show answer
One handler keeps responses consistent. class AppError extends Error { constructor(message, statusCode = 500) { super(message); this.statusCode = statusCode; this.isOperational = true; } } function errorHandler(err, req, res, next) { if (err.code === 11000) err = new AppError('Duplicate value', 409); const status = err.statusCode || 500; res.status(status).json({ message: err.isOperational ? err.message : 'Something went wrong' }); } app.use(errorHandler); // register last
04

An error in one dashboard widget crashes the entire React page. How do you contain it?

Save to ▾
Show answer
Wrap risky sections in error boundaries. An error boundary catches rendering errors in its subtree and shows fallback UI instead of unmounting the whole app. React still requires a class with getDerivedStateFromError and componentDidCatch, or you can use the react-error-boundary package. Place boundaries around each widget and the route level, log errors to monitoring, and offer a retry. They do not catch errors in event handlers or async code.
05

Every time a user types in an input inside a list item, the input loses focus. What could be the cause?

Save to ▾
Show answer
The component is likely being remounted on each render. Common causes are generating keys randomly, such as key={Math.random()}, defining a component inside another component's body so it gets a new identity every render, or using index keys while the list reorders. Use stable ids as keys and move inner component definitions to the module level so React preserves their DOM and state.
06

What is the difference between package.json and package-lock.json, and what do ^ and ~ mean?

Save to ▾
Show answer
package.json lists dependencies with version ranges, scripts and metadata. package-lock.json records the exact installed versions of every package, including nested ones, so every machine and CI build gets the same tree. Commit both and use npm ci in pipelines. A caret like ^4.18.2 allows minor and patch updates below 5.0.0; a tilde like ~4.18.2 allows only patch updates below 4.19.0.
07

What is a custom hook and what rules must hooks follow?

Save to ▾
Show answer
A custom hook is a function whose name starts with use and that calls other hooks to package reusable stateful logic, such as useFetch, useDebounce or useAuth. Each component using it gets its own state. Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions, so React can match state by call order. The eslint-plugin-react-hooks rules enforce this.
08

What is PM2 and why is it used to run Node.js in production?

Save to ▾
Show answer
PM2 is a process manager for Node.js. It keeps the app alive by restarting it after crashes, runs multiple instances in cluster mode to use all CPU cores, supports zero-downtime reloads with pm2 reload, manages logs and starts apps on server boot. Configuration lives in an ecosystem.config.js file. On container platforms like Kubernetes, the orchestrator often replaces PM2's restart and scaling role.
09

Why do applications use both access tokens and refresh tokens?

Save to ▾
Show answer
The access token is short-lived, for example 15 minutes, and is sent with every API request, so if stolen it is useful only briefly. The refresh token is long-lived, stored more securely in an httpOnly cookie, and is used only at a refresh endpoint to get new access tokens. Refresh tokens should be stored server-side or hashed so they can be revoked, and rotated on every use to detect theft.
10

What is a JWT and what are its three parts?

Save to ▾
Show answer
A JSON Web Token is a compact, URL-safe token made of three Base64URL-encoded parts separated by dots: the header with algorithm and type, the payload with claims like sub, role and exp, and the signature created from the header and payload using a secret or private key. The signature proves the token was not altered, but the payload is readable by anyone, so never put passwords or sensitive data in it.
11

What are React fragments and portals?

Save to ▾
Show answer
A fragment, written <>...</> or <Fragment key={id}>, groups children without adding an extra DOM element, which keeps tables and flex layouts valid. A portal, created with createPortal(child, domNode), renders children into a different DOM node such as document.body while keeping them in the same React tree, so context and event bubbling still work. Portals are used for modals, tooltips and toasts that must escape overflow hidden containers.
12

What are Mongoose middleware hooks and give a common use case.

Save to ▾
Show answer
Mongoose middleware are functions that run before or after operations such as save, validate, deleteOne, findOneAndUpdate and aggregate. A classic pre-save hook hashes a password only if it was modified: if (!this.isModified('password')) return; this.password = await bcrypt.hash(this.password, 12). Post hooks are used for logging or syncing. Note that query middleware like findOneAndUpdate does not trigger save hooks.
13

How do you plan a Node.js major version upgrade for a project your team maintains?

Save to ▾
Show answer
Situation: our services were on a Node version nearing end of life. Task: I owned the upgrade to the current LTS. Action: I read the changelog for breaking changes, upgraded locally, ran the test suite, fixed deprecated APIs and incompatible native packages, and rolled out to staging, then one production service, watching metrics. Result: all services moved within two sprints with no incidents, and I added an LTS calendar to our planning.
14

Compress a large file with gzip using streams in Node.js.

Save to ▾
Show answer
pipeline connects streams and handles errors and cleanup. import { createReadStream, createWriteStream } from 'node:fs'; import { createGzip } from 'node:zlib'; import { pipeline } from 'node:stream/promises'; await pipeline( createReadStream('access.log'), createGzip(), createWriteStream('access.log.gz') ); Memory stays low regardless of file size, and backpressure is managed automatically.
15

What is MongoDB and how is it different from a relational database?

Save to ▾
Show answer
MongoDB is a document database that stores data as flexible JSON-like documents in collections instead of rows in fixed tables. Related data can be embedded in one document, so many reads need no joins. Schemas are flexible, horizontal scaling through sharding is built in, and it supports indexes, aggregation and multi-document ACID transactions. Relational databases fit strongly structured data with many relationships and complex joins.
16

What are the main uses of useRef?

Save to ▾
Show answer
useRef returns a mutable object whose current property persists across renders without causing a re-render when changed. It is used to access DOM nodes, for example focusing an input or measuring size, and to store values like timer ids, previous values or the latest callback. Do not read or write ref.current during rendering for values that affect output, because React will not re-render when it changes.
17

What is NoSQL injection and how do you prevent it in a MongoDB app?

Save to ▾
Show answer
NoSQL injection happens when user input is placed directly into a query and contains operators. For example, a login body of { email: 'a@b.com', password: { $ne: null } } could match any password if passed straight to findOne. Prevent it by validating types with zod or Joi, casting inputs to strings, stripping keys starting with $ or containing dots, enabling Mongoose strictQuery, and never building $where queries from user input.
18

Compare Promise.all, Promise.allSettled, Promise.race and Promise.any.

Save to ▾
Show answer
Promise.all resolves with all results when every Promise fulfils and rejects as soon as any one rejects. Promise.allSettled always waits for all and returns status objects, useful when partial failure is fine. Promise.race settles with the first Promise to settle, often used for timeouts. Promise.any resolves with the first fulfilment and rejects with an AggregateError only if all reject, useful for trying multiple mirrors.
19

Some tests pass locally but fail randomly in CI. How do you handle flaky tests?

Save to ▾
Show answer
Rerun to confirm flakiness, then find the cause instead of adding retries. Common causes are shared database state between tests, tests depending on run order, real timers and dates, network calls to real services, and E2E tests using fixed waits instead of waiting for elements. Isolate data per test, mock time and external APIs, use proper async waits, and quarantine a flaky test with a ticket until fixed.
20

What does React.memo do and when is it useful?

Save to ▾
Show answer
React.memo wraps a component so it skips re-rendering when its props are shallowly equal to the previous props. It helps with expensive components that re-render often because the parent re-renders, such as rows in a large table. It fails if you pass new object, array or function props every render, so pair it with useMemo and useCallback. Measure with React DevTools Profiler before adding it.
21

What does lean() do in Mongoose and when should you use it?

Save to ▾
Show answer
By default Mongoose queries return full documents with change tracking, getters, virtuals and methods like save. Calling .lean() returns plain JavaScript objects, which uses much less memory and is noticeably faster. Use it for read-only endpoints such as lists and API responses. Skip it when you need to modify and save the document, or depend on virtuals and getters unless you add a lean plugin.
22

What is the difference between CommonJS and ES modules in Node.js?

Save to ▾
Show answer
CommonJS uses require and module.exports, loads synchronously and is the historic Node default. ES modules use import and export, are statically analysable, support top-level await and enable tree shaking. Node treats .mjs files, or .js files when package.json has type: module, as ESM. Modern Node versions can even require synchronous ES modules, but mixing systems still needs care, so new MERN projects usually pick ESM throughout.
23

Walk me through a MERN project you built, end to end.

Save to ▾
Show answer
Situation: I built a job portal as my major project. Task: let recruiters post jobs and students apply with resumes. Action: I designed MongoDB collections for users, jobs and applications with indexes, built an Express REST API with JWT auth and role checks, a React frontend with React Router and TanStack Query, uploaded resumes to cloud storage, wrote API tests and deployed with Docker. Result: 60 classmates used it during placement season.
24

Attackers are trying thousands of passwords on your login endpoint. How do you defend it?

Save to ▾
Show answer
Apply strict rate limits on login per IP and per account using a shared Redis store, add progressive delays or temporary account lockout after several failures, and show a CAPTCHA after repeated attempts. Return a generic error message so attackers cannot tell whether an email exists. Log and alert on spikes, check for breached passwords at signup, and offer two-factor authentication for sensitive accounts.
25

Implement your own version of Promise.all.

Save to ▾
Show answer
It must keep result order and reject on the first failure. function promiseAll(items) { return new Promise((resolve, reject) => { const results = []; let done = 0; if (items.length === 0) return resolve(results); items.forEach((item, i) => { Promise.resolve(item).then((value) => { results[i] = value; done += 1; if (done === items.length) resolve(results); }, reject); }); }); } Promise.resolve handles plain values mixed with Promises.
26

Write a debounce function in JavaScript.

Save to ▾
Show answer
Debounce delays a call until a quiet period has passed. Each new call clears the previous timer. function debounce(fn, delay = 300) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const onSearch = debounce((q) => fetchResults(q), 400); It relies on a closure over timer and keeps this and arguments intact.
27

A single-page app gets slower the longer a user keeps it open. What JavaScript memory leaks would you check for?

Save to ▾
Show answer
Look for event listeners, intervals and subscriptions added without cleanup, closures holding large objects, detached DOM nodes still referenced in variables, growing caches or global arrays, and WebSocket handlers registered on every render. In React, these usually come from useEffect without a cleanup function. Use the Chrome DevTools Memory tab to take heap snapshots before and after an action and compare retained objects.
28

Write a production Dockerfile for a Node.js Express API.

Save to ▾
Show answer
Keep the image small and run as a non-root user. FROM node:22-alpine WORKDIR /app ENV NODE_ENV=production COPY package*.json ./ RUN npm ci --omit=dev COPY src ./src USER node EXPOSE 5000 CMD ["node", "src/server.js"] Copying package files first lets Docker cache the dependency layer, so code changes rebuild quickly. Add a .dockerignore with node_modules and .env.
29

How do you add a timeout to a fetch call in Node.js?

Save to ▾
Show answer
Node 18 and later ship a global fetch. Use AbortSignal.timeout to cancel slow requests. async function getJSON(url) { try { const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (err) { if (err.name === 'TimeoutError') console.error('Request timed out'); throw err; } } Without a timeout, a hung upstream can hold connections open indefinitely.
30

Build a simple todo list in React with add and delete.

Save to ▾
Show answer
Update arrays immutably. function Todos() { const [todos, setTodos] = useState([]); const [text, setText] = useState(''); const add = (e) => { e.preventDefault(); if (!text.trim()) return; setTodos((t) => [...t, { id: crypto.randomUUID(), text }]); setText(''); }; const remove = (id) => setTodos((t) => t.filter((x) => x.id !== id)); return ( <form onSubmit={add}> <input value={text} onChange={(e) => setText(e.target.value)} /> <ul>{todos.map((t) => ( <li key={t.id}>{t.text} <button type='button' onClick={() => remove(t.id)}>x</button></li> ))}</ul> </form> ); }
31

What is CSRF and how do SameSite cookies help prevent it?

Save to ▾
Show answer
Cross-site request forgery tricks a logged-in user's browser into sending a request to your site from a malicious page, and the browser attaches the user's cookies automatically. SameSite=Lax blocks cookies on cross-site POST requests and SameSite=Strict blocks them on all cross-site requests, which stops most CSRF. For extra safety use CSRF tokens on state-changing routes, never change state with GET, and verify the Origin header.
32

Tell me about a time you had to deliver a frontend feature under a tight deadline.

Save to ▾
Show answer
Situation: a client demo was moved two days earlier and our filters page was half done. Task: deliver a working version in time. Action: I agreed a reduced scope with the lead, reused existing components, built the three most-used filters first and wrote quick tests for them, and kept the team updated each evening. Result: the demo went well and the remaining filters shipped in the next sprint.
33

Write an Express middleware that verifies a JWT from the Authorization header.

Save to ▾
Show answer
Reject missing or invalid tokens with 401. import jwt from 'jsonwebtoken'; export function requireAuth(req, res, next) { const header = req.headers.authorization || ''; const token = header.startsWith('Bearer ') ? header.slice(7) : null; if (!token) return res.status(401).json({ message: 'Token missing' }); try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({ message: 'Invalid or expired token' }); } } router.get('/me', requireAuth, getProfile);
34

You stored all comments inside each blog post document and some posts are now very large. How would you redesign it?

Save to ▾
Show answer
An unbounded embedded array risks hitting the 16 MB document limit and makes every post read and update heavy. Move comments to their own collection with a postId field and an index on { postId: 1, createdAt: -1 }, then paginate. Optionally keep a small embedded array of the latest few comments plus a commentCount on the post for fast first render. This is the subset pattern.
35

Tell me about a time you found and fixed a security issue in an application.

Save to ▾
Show answer
Situation: while testing an order history feature, I noticed changing the order id in the URL showed another user's order. Task: fix this insecure direct object reference before release. Action: I added an ownership check in the service layer so queries always filter by the logged-in user's id, wrote tests for cross-user access, and reviewed similar endpoints. Result: we fixed four endpoints and added ownership checks to our review checklist.
36

A search box fires an API request on every keystroke and overloads the backend. How would you solve it?

Save to ▾
Show answer
Debounce the input so the request goes out only after the user stops typing for around 300 ms. Also skip very short queries, cancel the previous request with AbortController so stale responses cannot overwrite newer ones, and cache recent results. On the server side, add rate limiting and an index on the searched field. Throttling is the alternative when you need periodic updates, like scroll tracking.

Few big employers listed in Chandigarh?

Many Chandigarh candidates also apply to teams in Gurgaon and to remote or hybrid roles. Practise the Gurgaon set as well.

Frequently asked questions

Which companies hire MERN Stack professionals in Chandigarh?

Companies with large offices in Chandigarh include many IT services and product firms. Use their company pages below to practise employer-specific sets.

Are MERN Stack interviews in Chandigarh different from other cities?

The questions depend more on the company than the city. Chandigarh's mix of employers decides the style: Interviews usually check strong fundamentals and practical tool skills

How do I find MERN Stack jobs in Chandigarh?

Shortlist companies with Chandigarh offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Chandigarh filter, and practise the questions on this page before each interview.