Skip to content

MERN Tech Lead Interview Questions & Answers

40 questions for MERN Tech Lead interviews — 24 medium, 16 hard.

About the MERN Tech Lead role

A MERN Tech Lead guides a team of developers delivering web products. Beyond hands-on coding in critical areas, you break down requirements, plan sprints with managers, define architecture and DevOps practices, review designs, and remove blockers. You represent the team in technical discussions with clients or stakeholders and are accountable for quality, security and delivery timelines across the frontend and backend.

Technical leadership Architecture Sprint planning DevOps practices Stakeholder communication
Solved for this roleStart 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

How is Docker used in a MERN project?

Save to ▾
Show answer
Docker packages each service with its runtime and dependencies into an image so it runs the same on every machine. Typically the Express API gets an image built from a Node base, the React app is built and served by Nginx, and MongoDB runs from the official image locally while production often uses MongoDB Atlas. docker compose starts all services with one command, with networks and volumes for persistent data.
02

How is Nginx used in front of a MERN application?

Save to ▾
Show answer
Nginx acts as a reverse proxy and web server. It serves the built React static files efficiently with caching and compression, proxies /api requests to Node instances, load balances across them, terminates HTTPS with certificates such as Let's Encrypt, and can apply rate limits and request size limits. For React Router, it uses try_files with a fallback to index.html so deep links work.
03

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

Your MERN product is expected to grow from 1,000 to 1 lakh daily users. How would you prepare the architecture?

Save to ▾
Show answer
Make the API stateless and run multiple instances behind a load balancer with autoscaling. Serve the React build and media from a CDN. Move sessions, rate limits and caches to Redis. Optimise MongoDB with proper indexes, a replica set, read preferences for analytics and plan sharding if data grows. Push slow work to queues, add monitoring and alerts, and load test before launch to find limits.
05

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

How would you achieve zero-downtime deployments for an Express API?

Save to ▾
Show answer
Run at least two instances behind a load balancer and use rolling or blue-green deployments: start new instances, wait for health and readiness checks to pass, shift traffic, then drain and stop old instances with graceful shutdown. PM2 reload or Kubernetes rolling updates handle this. Keep database migrations backward compatible, adding fields before code uses them, so old and new versions can run together.
07

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

What are replica sets and sharding in MongoDB, and how do you choose a shard key?

Save to ▾
Show answer
A replica set is a primary plus secondaries holding copies of data, giving automatic failover and optional read scaling. Sharding splits a collection across multiple shards for horizontal scaling of data size and write throughput. A good shard key has high cardinality, evenly distributed writes and matches common queries so they target one shard. Monotonic keys like createdAt create hot spots unless hashed.
09

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

How would you structure the folders of a production Express API?

Save to ▾
Show answer
A layered structure keeps responsibilities clear: src/routes for route definitions, src/controllers for request and response handling, src/services for business logic, src/models for Mongoose schemas, src/middlewares for auth, validation and errors, src/config for environment and database setup, src/utils for helpers, and tests alongside or in a tests folder. Keep app.js, which builds the app, separate from server.js, which listens, so tests can import the app.
11

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

Tell me about a time you improved the performance of a slow database-driven feature.

Save to ▾
Show answer
Situation: our admin orders page took 8 seconds to load. Task: I was asked to fix it within a sprint. Action: I profiled the API, found a populate on every row plus an unindexed sort, added a compound index, replaced populate with a single $lookup projecting only needed fields, and used lean. Result: load time dropped below 600 ms and I shared an indexing checklist with the team.
13

How would you use Redis caching in a MERN backend and what are the pitfalls?

Save to ▾
Show answer
Use the cache-aside pattern: check Redis for a key, return it on a hit, otherwise query MongoDB, store the result with a TTL and return it. Good targets are expensive, frequently read data like product listings. Pitfalls include stale data, so invalidate or update keys on writes; cache stampede when many requests miss at once, solved with locking or early refresh; and memory limits, managed with eviction policies.
14

A developer accidentally pushed the .env file with the MongoDB password and JWT secret to a public repository. What do you do?

Save to ▾
Show answer
Treat the secrets as compromised immediately. Rotate the MongoDB user password, the JWT secret and any API keys; rotating the JWT secret logs everyone out, which is acceptable. Check database and cloud logs for suspicious access. Remove the file, add .env to .gitignore, and purge it from history with a tool like git filter-repo, though rotation matters more. Enable secret scanning and pre-commit hooks to prevent repeats.
15

Users can upload profile pictures and documents. What security measures do you put in place?

Save to ▾
Show answer
Enforce size limits and an allowlist of types, checking magic bytes rather than trusting the extension or Content-Type. Rename files with random ids, store them in object storage outside the web root, and serve them from a separate domain or with Content-Disposition attachment for documents. Strip image metadata, scan for malware where needed, use pre-signed URLs with expiry for private files, and never execute or include uploaded files.
16

Write an asyncHandler wrapper for Express 4 route handlers.

Save to ▾
Show answer
It catches rejected Promises and forwards them to error middleware. const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); router.get('/:id', asyncHandler(async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).json({ message: 'Not found' }); res.json(user); })); Express 5 does this automatically, but many existing codebases still use this pattern.
17

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

How do you handle pressure to ship quickly when you think a feature is not secure yet?

Save to ▾
Show answer
Situation: a product manager wanted a file-sharing feature live by Friday, but uploads had no type or access checks. Task: protect users without blocking the launch. Action: I explained the risk in business terms, proposed shipping with private pre-signed links and type limits first, and deferring sharing features to the next sprint. Result: we launched on time with the risky part removed, and the full feature followed a week later.
19

How does Sign in with Google work using OAuth 2.0 and OpenID Connect?

Save to ▾
Show answer
The app redirects the user to Google's authorization endpoint with client id, redirect URI, scopes like openid email and a state value. After consent, Google redirects back with an authorization code, and the backend exchanges it for an ID token and access token. With OpenID Connect, the ID token is a signed JWT whose signature, audience and expiry you verify, then you create your own session. PKCE protects the code exchange.
20

What strategies can you use to version a REST API?

Save to ▾
Show answer
The most common approach is URL versioning such as /api/v1/orders, which is simple and cache friendly. Alternatives are a custom header or a media type like Accept: application/vnd.app.v2+json, which keeps URLs clean but is harder to test in a browser. Whatever you choose, make additive changes without a new version, announce deprecations, and run old and new versions side by side during migration.
21

How do you protect a public Express API from abuse and brute-force traffic?

Save to ▾
Show answer
Add rate limiting with express-rate-limit, using a Redis store when running multiple instances, and apply stricter limits to login and OTP routes. Set request body size limits, validate all input, require authentication on non-public routes, add helmet headers and timeouts. At the edge, a CDN or web application firewall can block bots and DDoS traffic before it reaches Node. Return 429 with a Retry-After header.
22

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

Should you store a JWT in localStorage or in an httpOnly cookie?

Save to ▾
Show answer
localStorage is readable by any JavaScript on the page, so an XSS bug can steal the token. An httpOnly, Secure cookie cannot be read by JavaScript, which protects against token theft through XSS, but cookies are sent automatically, so you must defend against CSRF with SameSite=Lax or Strict and CSRF tokens where needed. A common pattern keeps the refresh token in an httpOnly cookie and the access token in memory.
24

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

What are the important changes in Express 5 compared to Express 4?

Save to ▾
Show answer
Express 5 requires a modern Node version and forwards rejected Promises from async handlers to error middleware. Route path syntax moved to a newer path-to-regexp, so wildcards must be named, like /*splat, and regex-style characters in strings are no longer supported. Deprecated methods like res.send(status, body) were removed, req.query is read-only, and req.body is undefined unless a body parser runs.
26

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

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

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

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
30

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

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

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

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

Write a reusable validation middleware for Express using zod.

Save to ▾
Show answer
Validate before the controller runs and return 400 on failure. import { z } from 'zod'; const validate = (schema) => (req, res, next) => { const result = schema.safeParse(req.body); if (!result.success) { return res.status(400).json({ errors: result.error.issues }); } req.body = result.data; next(); }; const userSchema = z.object({ name: z.string().min(2), email: z.string().email() }); router.post('/users', validate(userSchema), createUser);
35

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
36

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

A MongoDB query on an orders collection takes 3 seconds. How do you diagnose and fix it?

Save to ▾
Show answer
Run the query with .explain('executionStats') and check whether the winning plan is COLLSCAN and how totalDocsExamined compares to nReturned. Create an index matching the filter and sort, following ESR, and confirm it becomes IXSCAN. Also project only needed fields, add limits, use lean in Mongoose, and check the profiler or Atlas Performance Advisor for other slow queries. Re-test with production-like data volume.
38

What is libuv and which operations use the Node.js thread pool?

Save to ▾
Show answer
libuv is the C library that provides Node's event loop and asynchronous I/O. Network I/O uses non-blocking OS mechanisms like epoll or IOCP, so it does not use the pool. The thread pool, four threads by default, handles file system calls, DNS lookup, zlib compression and crypto functions like pbkdf2 and scrypt. Heavy bcrypt or crypto load can saturate it; UV_THREADPOOL_SIZE can increase it.
39

Write an Axios interceptor in React that refreshes the access token on a 401 response.

Save to ▾
Show answer
Retry the failed request once after refreshing. const api = axios.create({ baseURL: '/api', withCredentials: true }); let accessToken = null; api.interceptors.request.use((config) => { if (accessToken) config.headers.Authorization = `Bearer ${accessToken}`; return config; }); api.interceptors.response.use((res) => res, async (error) => { const original = error.config; if (error.response?.status === 401 && !original._retry) { original._retry = true; const { data } = await api.post('/auth/refresh'); accessToken = data.accessToken; return api(original); } return Promise.reject(error); }); In production, queue parallel requests behind one shared refresh promise.
40

Design a payment endpoint so that client retries never charge a user twice.

Save to ▾
Show answer
Make the endpoint idempotent with an idempotency key. The client generates a unique key per checkout and sends it in a header. The server stores the key with a unique index along with the request hash and the result. If the same key arrives again, return the stored response instead of reprocessing. Use a status field for in-progress requests and verify final status through the payment gateway webhook.

Frequently asked questions

What does a MERN Tech Lead do?

A MERN Tech Lead guides a team of developers delivering web products. Beyond hands-on coding in critical areas, you break down requirements, plan sprints with managers, define architecture and DevOps practices, review designs, and remove blockers. You represent the team in technical discussions with clients or stakeholders and are accountable for quality, security and delivery timelines across the frontend and backend.

Which skills are tested in a MERN Tech Lead interview?

Expect questions on Technical leadership, Architecture, Sprint planning, DevOps practices, Stakeholder communication. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a MERN Tech Lead interview?

Revise Express.js and REST APIs, Authentication and Security, Testing, Deployment and DevOps first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.