Skip to content

MERN Stack Interview Questions for 5 Years Experience

40 questions with answers for candidates with 5 years of experience — 1 easy, 24 medium, 15 hard.

What interviewers expect: 5 years experience

At five years, interviews test architecture and leadership. You may design a scalable MERN system with load balancing, queues, sharding and observability, plan a migration such as moving to TypeScript or a new framework, and discuss security reviews. Behavioural rounds explore how you handle disagreements, estimate work, mentor developers and make decisions under deadlines while keeping quality high.

This set is weighted towards Testing, Deployment and DevOps (8), React Hooks, State and Performance (7), MongoDB and Mongoose (6), Modern JavaScript (ES6+) (5).

Scalable architecture Security and reliability Migrations Mentoring and estimation
Solved at this levelStart 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

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.
02

What is mocking and when should you mock in tests?

Save to ▾
Show answer
Mocking replaces a real dependency with a controlled fake so tests are fast, isolated and deterministic. Mock things you do not own or that are slow or unpredictable: payment gateways, email services, third-party APIs, time and random values. In React tests, Mock Service Worker intercepts network requests. Avoid mocking everything, especially your own database layer in integration tests, or tests will pass while real code fails.
03

Your API has 40 routes and each returns errors in a different format. How would you standardise this?

Save to ▾
Show answer
Create a custom AppError class with statusCode and code fields, throw it from services and controllers, and handle every error in one central error middleware that returns a consistent shape such as { success: false, error: { code, message, details } }. Map validation, Mongoose cast and duplicate key errors to proper status codes there. Document the format in OpenAPI so the React team handles errors uniformly.
04

What does a CI/CD pipeline for a MERN application usually include?

Save to ▾
Show answer
On every pull request, continuous integration installs dependencies with npm ci, runs lint, type checks, unit and integration tests, and builds the frontend. On merge to main, continuous delivery builds Docker images or artifacts, tags them with the commit, pushes to a registry, deploys to staging, runs smoke tests and then promotes to production, often with manual approval. GitHub Actions, GitLab CI and Jenkins are common tools.
05

Compare session-based authentication with JWT-based authentication.

Save to ▾
Show answer
With sessions, the server stores session data in a store such as Redis and the browser holds only a session id cookie; revoking is easy, but every request needs a lookup. With JWTs, the token itself carries signed claims, so servers can verify it without a lookup, which suits microservices and mobile clients. JWTs are harder to revoke before expiry, so keep them short-lived and pair them with refresh tokens.
06

Write a deep clone function that handles nested objects, arrays and dates.

Save to ▾
Show answer
In production prefer structuredClone, but interviewers often ask for a manual version. function deepClone(value, seen = new WeakMap()) { if (value === null || typeof value !== 'object') return value; if (value instanceof Date) return new Date(value); if (seen.has(value)) return seen.get(value); const copy = Array.isArray(value) ? [] : {}; seen.set(value, copy); for (const key of Object.keys(value)) copy[key] = deepClone(value[key], seen); return copy; } The WeakMap prevents infinite loops on circular references.
07

Fetch a list of users from an API inside useEffect with proper cleanup.

Save to ▾
Show answer
AbortController cancels the request if the component unmounts. function Users() { const [users, setUsers] = useState([]); const [error, setError] = useState(null); useEffect(() => { const controller = new AbortController(); fetch('/api/users', { signal: controller.signal }) .then((r) => r.json()) .then(setUsers) .catch((e) => { if (e.name !== 'AbortError') setError(e); }); return () => controller.abort(); }, []); if (error) return <p>Failed to load</p>; return <ul>{users.map((u) => <li key={u._id}>{u.name}</li>)}</ul>; }
08

What are the key new features in React 19?

Save to ▾
Show answer
React 19 added Actions, letting async functions handle form submissions with pending and error state; hooks such as useActionState, useFormStatus and useOptimistic; the use API to read Promises and context; ref as a normal prop instead of forwardRef; support for document metadata tags like title inside components; and stable Server Components. The separate React Compiler can automatically memoize components, reducing manual useMemo and useCallback.
09

How do transactions work in MongoDB and when do you need them?

Save to ▾
Show answer
Single-document writes are already atomic, so good embedded design avoids most transactions. Multi-document ACID transactions are available on replica sets and sharded clusters, not on a standalone server. In Mongoose, start a session, call session.withTransaction() and pass the session to every operation. Use them for cases like transferring wallet balance between two users. They add latency and should stay short, ideally under one second.
10

Tell me about a time you disagreed with a teammate about an API design decision.

Save to ▾
Show answer
Situation: a frontend teammate wanted one endpoint returning the entire dashboard, while I preferred separate resource endpoints. Task: we needed a decision before sprint planning. Action: I listed trade-offs, measured payload size and call counts for both, and we agreed on resource endpoints plus one aggregated summary endpoint for the first screen. Result: the dashboard loaded faster and the API stayed reusable for the mobile app.
11

What is the aggregation pipeline and what are its common stages?

Save to ▾
Show answer
The aggregation pipeline processes documents through a sequence of stages, each transforming the stream. Common stages are $match to filter, $group to aggregate with operators like $sum and $avg, $project or $addFields to shape fields, $sort, $limit, $skip, $lookup to join another collection, $unwind to flatten arrays and $facet for multiple outputs. Put $match and $sort early so they can use indexes and reduce the data volume.
12

Write a reusable useFetch custom hook.

Save to ▾
Show answer
It returns data, error and loading state and aborts stale requests. function useFetch(url) { const [state, setState] = useState({ data: null, error: null, loading: true }); useEffect(() => { const controller = new AbortController(); setState((s) => ({ ...s, loading: true })); fetch(url, { signal: controller.signal }) .then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); }) .then((data) => setState({ data, error: null, loading: false })) .catch((error) => { if (error.name !== 'AbortError') setState({ data: null, error, loading: false }); }); return () => controller.abort(); }, [url]); return state; }
13

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.
14

What is the difference between server state and client state, and why use a library like TanStack Query?

Save to ▾
Show answer
Client state is UI data owned by the browser, like modal open or selected tab. Server state lives in the database, can be changed by others, and is only a cached copy in the browser. TanStack Query manages server state with caching, deduplication, background refetching, retries, pagination and mutations with cache invalidation. This removes much hand-written useEffect fetching and stops global stores from holding stale API data.
15

Your Express API slows down badly during peak traffic. How do you find and fix the bottleneck?

Save to ▾
Show answer
Measure first: add request timing logs or APM tracing to find slow endpoints, then check whether time goes to the database, external calls or CPU. Use explain() for slow queries and add indexes, cache hot read endpoints in Redis, enable compression, paginate large responses and remove synchronous code from handlers. Then scale horizontally with multiple instances behind a load balancer and load test with k6 or autocannon.
16

Create a compound index for a user's order history query and verify it is used.

Save to ▾
Show answer
Query: orders of one user, newest first. db.orders.createIndex({ userId: 1, createdAt: -1 }) db.orders.find({ userId: ObjectId('...') }) .sort({ createdAt: -1 }) .limit(20) .explain('executionStats') Check that the winning plan shows IXSCAN, not COLLSCAN, and that totalDocsExamined is close to nReturned. In Mongoose, declare it with orderSchema.index({ userId: 1, createdAt: -1 }).
17

Tell me about a time you led a technical migration in a frontend codebase.

Save to ▾
Show answer
Situation: our React app still used Create React App and class components, and builds took several minutes. Task: as the senior developer I proposed moving to Vite and hooks. Action: I wrote a migration plan, moved the build tool first behind a feature branch, fixed environment variable names, then converted components gradually with tests. Result: dev server start went from 40 seconds to 2, builds became much faster, and the team adopted hooks patterns.
18

What are streams in Node.js and what types exist?

Save to ▾
Show answer
Streams process data in chunks instead of loading it all into memory. The four types are Readable (file read, HTTP request), Writable (file write, HTTP response), Duplex (TCP socket) and Transform (gzip, encryption), which modifies data as it passes. Streams handle backpressure, pausing the source when the destination is slow. pipeline() from node:stream/promises connects them safely and handles errors and cleanup.
19

How do you debug a JavaScript bug that a user reports but you cannot reproduce locally?

Save to ▾
Show answer
Situation: a user reported a checkout button doing nothing, but it worked for me. Task: find the cause quickly. Action: I asked for browser, device and steps, checked our error-tracking logs, and found a TypeError only on an older Safari version due to an unsupported method. I reproduced it on a cloud device, added a polyfill and a test. Result: the fix shipped the same day and I added browser targets to our build.
20

Write a Supertest integration test for a POST /api/users endpoint.

Save to ▾
Show answer
Import the app, not the running server. import request from 'supertest'; import app from '../src/app.js'; describe('POST /api/users', () => { it('creates a user', async () => { const res = await request(app) .post('/api/users') .send({ name: 'Aman', email: 'aman@test.com' }) .expect(201); expect(res.body.email).toBe('aman@test.com'); }); it('rejects invalid email', async () => { await request(app).post('/api/users').send({ name: 'A', email: 'x' }).expect(400); }); }); Connect to mongodb-memory-server in a beforeAll hook.
21

Write a Redux Toolkit slice that fetches products with createAsyncThunk.

Save to ▾
Show answer
The slice handles pending, fulfilled and rejected states. export const fetchProducts = createAsyncThunk('products/fetch', async () => { const res = await fetch('/api/products'); return res.json(); }); const productsSlice = createSlice({ name: 'products', initialState: { items: [], status: 'idle', error: null }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchProducts.pending, (s) => { s.status = 'loading'; }) .addCase(fetchProducts.fulfilled, (s, a) => { s.status = 'done'; s.items = a.payload; }) .addCase(fetchProducts.rejected, (s, a) => { s.status = 'failed'; s.error = a.error.message; }); } }); export default productsSlice.reducer;
22

What does lifting state up mean in React?

Save to ▾
Show answer
When two or more components need the same data, you move that state to their closest common parent and pass it down as props, along with functions to update it. For example, a filter bar and a product list both depend on the selected category, so the page component holds the category state. This keeps one source of truth and avoids components getting out of sync.
23

Duplicate user accounts with the same email are being created even though the code checks for an existing email first. Why, and how do you fix it?

Save to ▾
Show answer
Check-then-insert is a race condition: two concurrent requests both see no user and both insert. The real fix is a unique index on email, normalised to lowercase, so the database rejects the second insert with error code 11000. Catch that error and return 409 Conflict. Clean up existing duplicates before building the index, otherwise index creation fails.
24

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.
25

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> ); }
26

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.
27

When a user logs out or changes password, how do you make sure their existing JWTs stop working?

Save to ▾
Show answer
Stateless JWTs stay valid until expiry, so keep access tokens short-lived and revoke refresh tokens by deleting or flagging them in the database. For immediate invalidation, store a tokenVersion or passwordChangedAt on the user and include it in the token; the auth middleware rejects tokens with an older version. Alternatively keep a Redis denylist of token ids until they expire. Clear the refresh cookie on logout.
28

Group an array of order objects by their status using reduce.

Save to ▾
Show answer
reduce builds an object whose keys are statuses and values are arrays. const grouped = orders.reduce((acc, order) => { (acc[order.status] ||= []).push(order); return acc; }, {}); // { paid: [...], pending: [...] } Newer runtimes also offer Object.groupBy(orders, (o) => o.status), which returns the same shape with a null prototype.
29

You need to rename a field and change its type across 20 million documents in production. How do you do it safely?

Save to ▾
Show answer
Avoid a single big blocking update. Make the application read both old and new formats first, then run a batched migration script that processes documents in chunks by _id range with bulkWrite, throttled and resumable, or an updateMany with an aggregation pipeline during low traffic. Track progress, verify counts, back up first, then remove the old-field handling in a later release.
30

What is the output order of console.log('A'), setTimeout(() => console.log('B'), 0), Promise.resolve().then(() => console.log('C')) and console.log('D')?

Save to ▾
Show answer
The output is A, D, C, B. A and D are synchronous and run immediately on the call stack. The Promise callback C goes into the microtask queue, and the setTimeout callback B goes into the macrotask queue. After the synchronous code finishes, the event loop drains all microtasks first, printing C, and only then runs the timer callback, printing B, even with a 0 ms delay.
31

Describe a production issue you handled in a Node.js service.

Save to ▾
Show answer
Situation: our order API started timing out every evening at peak. Task: as the on-call developer I had to restore it. Action: I checked logs and metrics, found event-loop lag spikes, and traced them to a synchronous CSV export running inside a request. I moved the export to a background job and added event-loop lag alerts. Result: p95 latency dropped from 4 seconds to 300 ms and timeouts stopped.
32

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.
33

Write a GitHub Actions workflow that tests and builds a MERN project on every pull request.

Save to ▾
Show answer
Run server and client jobs in parallel. name: ci on: pull_request: push: branches: [main] jobs: server: runs-on: ubuntu-latest defaults: run: working-directory: server steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm cache-dependency-path: server/package-lock.json - run: npm ci - run: npm run lint - run: npm test client: runs-on: ubuntu-latest defaults: run: working-directory: client steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - run: npm ci - run: npm run build
34

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.
35

You need to call an external API 500 times but it allows only 5 concurrent requests. How would you implement this?

Save to ▾
Show answer
Use a concurrency-limited queue. Keep a pool of five workers; each worker picks the next item from a shared index, awaits the request, and loops until the list is exhausted. Run the workers with Promise.all. Libraries such as p-limit do this neatly. Add retries with backoff for 429 responses and collect failures separately instead of failing the whole batch, so one bad item does not stop the job.
36

Your chat feature uses Socket.IO and must now run on multiple Node instances. What changes are needed?

Save to ▾
Show answer
Each instance only knows its own connected sockets, so a message emitted on one would not reach users on another. Add the Socket.IO Redis adapter, or a similar pub/sub adapter, so events are broadcast across instances. Enable sticky sessions at the load balancer if HTTP long-polling fallback is used. Store presence and room membership in Redis, persist messages in MongoDB, and authenticate sockets with tokens during the handshake.
37

Explain CSR, SSR, hydration and React Server Components.

Save to ▾
Show answer
With client-side rendering, the browser downloads JavaScript and builds the page, which is slower for first paint and SEO. Server-side rendering sends ready HTML, then hydration attaches React event handlers in the browser. React Server Components run only on the server, can query data directly, and send no JavaScript for themselves, while client components marked use client handle interactivity. Frameworks like Next.js implement these patterns.
38

Write a docker-compose file to run a MERN app locally.

Save to ▾
Show answer
Three services on one network: services: mongo: image: mongo:8 volumes: - mongo-data:/data/db api: build: ./server environment: MONGO_URI: mongodb://mongo:27017/shop JWT_SECRET: dev-secret ports: - "5000:5000" depends_on: - mongo web: build: ./client ports: - "8080:80" depends_on: - api volumes: mongo-data: The API reaches the database through the service name mongo.
39

How does error-handling middleware work in Express, and what changed in Express 5?

Save to ▾
Show answer
Error handlers have four parameters, (err, req, res, next), and Express routes errors to them when you call next(err) or throw synchronously. In Express 4, rejected Promises in async handlers were not caught, so you needed try/catch or a wrapper. Express 5 automatically forwards rejected Promises from async handlers to the error middleware. Register the error handler after all routes and avoid leaking stack traces in production.
40

Memory usage of a production Node.js service keeps rising until it restarts. How do you investigate?

Save to ▾
Show answer
First confirm the trend with monitoring of heapUsed and RSS. Reproduce in staging under load, then take heap snapshots with --inspect and Chrome DevTools, or use --heapsnapshot-signal, and compare snapshots to find growing object types and their retainers. Common causes are unbounded in-memory caches, listeners added per request, global arrays and unclosed timers. Fix the root cause, add a bounded LRU cache, and set alerts.

Frequently asked questions

What is asked in MERN Stack interviews for 5 years of experience?

At five years, interviews test architecture and leadership. You may design a scalable MERN system with load balancing, queues, sharding and observability, plan a migration such as moving to TypeScript or a new framework, and discuss security reviews. Behavioural rounds explore how you handle disagreements, estimate work, mentor developers and make decisions under deadlines while keeping quality high.

How many questions should I practise before a MERN Stack interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 5 years of experience?

Focus first on Scalable architecture, Security and reliability, Migrations, Mentoring and estimation.