36 practice questions with answers for MERN Stack interviews in Nagpur.
MERN Stack jobs in Nagpur
Nagpur's MIHAN SEZ hosts IT-services and BFSI delivery centres, giving central India a steady market for data and QA roles. Interviews are usually service-company style, with aptitude, technical and HR rounds.
Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Nagpur.
Solved for NagpurStart 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
Two sibling components need to share data. How do you handle it?
Lift the shared state to their nearest common parent and pass the value to one sibling and an updater to the other. If the data is needed by many components deep in the tree, use Context or a state library like Zustand or Redux Toolkit. If the data comes from the server, a data-fetching library like TanStack Query can share the cached result across components.
02
What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?
process.nextTick queues a callback to run right after the current operation, before Promise microtasks and before the event loop continues. setImmediate runs in the check phase after poll. setTimeout with 0 runs in the timers phase once at least about 1 ms has passed. Overusing nextTick recursively can starve I/O, so setImmediate is the safer way to defer heavy work.
03
Write an Express middleware that verifies a JWT from the Authorization header.
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.
05
Write a central error-handling middleware with a custom AppError class.
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.
BSON is the binary format MongoDB uses to store documents. It extends JSON with types like Date, ObjectId, Decimal128, binary data and 32 or 64-bit integers, and is fast to traverse. ObjectId is the default 12-byte _id value made of a 4-byte timestamp, a 5-byte random value and a 3-byte counter. Because it starts with a timestamp, ObjectIds roughly sort by creation time.
08
How do class component lifecycle methods map to hooks?
componentDidMount maps to useEffect with an empty dependency array. componentDidUpdate maps to useEffect with specific dependencies. componentWillUnmount maps to the cleanup function returned from useEffect. shouldComponentUpdate is roughly React.memo, and getDerivedStateFromProps is usually replaced by computing values during render. The mindset shifts from lifecycle moments to synchronising with external systems whenever certain values change.
Use the functional updater when the new value depends on the old one.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<button onClick={() => setCount((c) => c - 1)}>-</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
Hoisting means declarations are processed before code runs. Function declarations are hoisted fully, so you can call them before they appear. var declarations are hoisted but initialised to undefined, so console.log(x) before var x = 5 prints undefined. let, const and class declarations are hoisted too, but accessing them before the declaration throws a ReferenceError because of the temporal dead zone. Function expressions assigned to variables follow the variable rules.
11
What is the Context API and when should you avoid it?
Context passes data through the component tree without prop drilling. You create it with createContext, provide a value with a Provider and read it with useContext, or the newer use API. It suits low-frequency global data like theme, language and logged-in user. Avoid it for frequently changing large state, because every consumer re-renders when the value changes; split contexts or use Zustand or Redux Toolkit instead.
12
An error in one dashboard widget crashes the entire React page. How do you contain it?
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.
13
Explain indexes in MongoDB, compound indexes and the ESR rule.
An index is a sorted structure that lets queries avoid scanning every document. A compound index covers multiple fields in order, like { userId: 1, createdAt: -1 }, and supports queries on its leading prefix. The ESR guideline says order fields as Equality first, then Sort, then Range. Indexes speed reads but slow writes and use memory, so create them for real query patterns and drop unused ones.
14
Write a docker-compose file to run a MERN app locally.
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.
15
What are the important changes in Express 5 compared to Express 4?
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.
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.
17
Your script crashes with out of memory while reading a 5 GB log file. How would you rewrite it?
fs.readFile loads the whole file into memory, which exceeds the heap. Use a stream instead: fs.createReadStream with readline lets you process one line at a time with for await, keeping memory flat. If you need to transform and write output, connect read, transform and write streams with pipeline so backpressure and errors are handled. Increasing --max-old-space-size only hides the real problem.
18
How does the JavaScript event loop work with microtasks and macrotasks?
JavaScript runs one call stack. When the stack is empty, the event loop first drains the entire microtask queue, which holds Promise callbacks, queueMicrotask and await continuations. Only then does it pick the next macrotask, such as a setTimeout callback, an I/O callback or a UI event. This is why a resolved Promise callback always runs before a setTimeout of 0 ms scheduled at the same time.
19
Write a function to flatten a nested array without using Array.prototype.flat.
Recursion with reduce is the cleanest approach.
function flatten(arr) {
return arr.reduce((acc, item) =>
Array.isArray(item) ? acc.concat(flatten(item)) : acc.concat(item), []);
}
flatten([1, [2, [3, [4]]], 5]); // [1, 2, 3, 4, 5]
For very deep arrays, an iterative version with an explicit stack avoids hitting the recursion limit.
20
Write a production Dockerfile for a Node.js Express API.
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.
21
A for loop using var with setTimeout inside prints 3, 3, 3 instead of 0, 1, 2. Why, and how do you fix it?
var is function-scoped, so all three callbacks close over the same variable, which has become 3 by the time the timers fire. The simplest fix is to declare the loop variable with let, because let creates a fresh binding for every iteration. Older fixes include wrapping the body in an immediately invoked function or passing i as the third argument to setTimeout.
22
How do you implement code splitting in a React app?
Use dynamic import with React.lazy, for example const Admin = lazy(() => import('./Admin')), and wrap it in a Suspense boundary with a fallback. Bundlers like Vite then create a separate chunk that loads only when needed. Split by route first, then by heavy components like charts, editors and maps. Preload likely next routes on hover, and check results with a bundle analyser such as rollup-plugin-visualizer.
23
What is the aggregation pipeline and what are its common stages?
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.
24
Your app needs user, editor and admin roles with different permissions. How would you implement it?
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.
25
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?
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.
26
Why do you want to work as a MERN stack developer?
I enjoy building complete products, and MERN lets me use one language, JavaScript, across the database queries, the API and the user interface. In my projects, such as a job portal with React, Express and MongoDB, I liked seeing a feature go from schema to screen. The stack is widely used by startups and service companies in India, and I want to grow into a full stack engineer who owns features end to end.
27
Write a register endpoint that hashes the password with bcrypt.
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.
29
A developer accidentally pushed the .env file with the MongoDB password and JWT secret to a public repository. What do you do?
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.
30
After deploying a React app, refreshing on a page like /dashboard shows a 404 error. Why, and how do you fix it?
With client-side routing, /dashboard exists only inside React Router, not as a file on the server. When the browser requests it directly, the web server finds no file and returns 404. Configure the server to fall back to index.html for unknown paths: try_files $uri /index.html in Nginx, a rewrite rule on static hosts, or a catch-all route in Express that serves index.html after the API routes.
31
How do you add a timeout to a fetch call in Node.js?
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.
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.
33
What are Mongoose middleware hooks and give a common use case.
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.
34
Write an async helper that retries a failing call with exponential backoff.
Wait longer after each failure and give up after a limit.
async function retry(fn, retries = 3, base = 500) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const wait = base * 2 ** attempt + Math.random() * 100;
await new Promise((r) => setTimeout(r, wait));
}
}
}
The random jitter stops many clients from retrying at the same moment.
35
How do environment variables work in a Vite React app compared to a Node.js backend?
In Node, process.env is read at runtime on the server, so secrets are safe there. In a Vite app, only variables prefixed with VITE_ are exposed, through import.meta.env, and they are embedded into the JavaScript bundle at build time. Anything in the frontend bundle is public, so never put database passwords or secret keys there. Changing a frontend variable requires a rebuild.
36
Create an AuthContext with a provider and a custom hook.
Which companies hire MERN Stack professionals in Nagpur?
Companies with large offices in Nagpur include Persistent Systems, GlobalLogic. Use their company pages below to practise employer-specific sets.
Are MERN Stack interviews in Nagpur different from other cities?
The questions depend more on the company than the city. Nagpur's mix of employers decides the style: Interviews are usually service-company style, with aptitude, technical and HR rounds
How do I find MERN Stack jobs in Nagpur?
Shortlist companies with Nagpur offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Nagpur filter, and practise the questions on this page before each interview.