MERN Stack Interview Questions and Answers

MERN interviews move across all four layers in one sitting, so you need to show how a request travels from a React component through an Express route to MongoDB and back. The questions are grouped by layer, with a final section on the full-stack scenarios that tie them together.

51 questions with answersLevels: Fresher to SeniorUpdated November 2026

MongoDB and Mongoose

Database questions specific to the MERN stack.

Q1.What is MongoDB?

A document database that stores data as BSON documents, which look like JSON with extra types such as ObjectId and Date. Documents in a collection can have different fields, and the database scales with replica sets and sharding.

Q2.When should you embed and when should you reference documents?

Embed data that is read together and bounded in size, such as an address inside a user. Reference data that grows without limit or is shared, such as orders for a customer. The 16 MB document limit and update patterns guide the choice.

Q3.What is Mongoose and why use it?

An ODM for MongoDB in Node.js. It adds schemas, validation, type casting, middleware hooks, virtuals and population on top of the native driver, which brings structure to a schemaless database.

Q4.What does populate do in Mongoose?

It replaces stored ObjectId references with the referenced documents by running extra queries. It is convenient, but on large lists it can be slow, so use it with select and limits or use an aggregation $lookup.

Q5.What is the aggregation pipeline?

A sequence of stages that process documents, such as $match, $group, $sort, $project, $lookup and $unwind. It is used for reports, joins and transformations inside the database.

Q6.How do indexes work in MongoDB?

They are B-tree structures on fields, like in SQL databases. Without an index on a query field, MongoDB scans the whole collection. Use compound indexes that follow the equality, sort, range rule and check with explain().

Q7.Does MongoDB support transactions?

Yes. Multi-document ACID transactions work on replica sets and sharded clusters. They have a cost, so good schema design that keeps related data in one document is still preferred.

Q8.What is the difference between find and findOne, and what does lean() do?

find returns a cursor or array of matching documents, findOne returns the first match or null. lean() returns plain JavaScript objects instead of full Mongoose documents, which is faster for read-only queries.

Q9.What are Mongoose middleware hooks?

Functions that run before or after operations like save, validate or findOneAndUpdate. A pre-save hook is often used to hash passwords. Note that query middleware and document middleware fire for different methods.

Q10.How do you paginate in MongoDB?

skip and limit is simple but gets slow on large offsets. Range-based pagination using the last _id or a sorted field with an index is faster and stable.

Q11.What is a replica set?

A group of MongoDB servers with one primary that takes writes and secondaries that copy its data. If the primary fails, an election promotes a secondary automatically.

Q12.What is an ObjectId?

The default 12-byte _id value in MongoDB. It contains a timestamp, a random value and a counter, so it is unique across machines and roughly sortable by creation time.

Q13.What is the difference between updateOne with $set and replacing a document?

$set changes only the listed fields and leaves the rest. Replacing the document with replaceOne swaps the whole document, so fields you do not include are lost.

Q14.What are TTL indexes?

Indexes on a date field with expireAfterSeconds, so MongoDB deletes documents automatically after that time. They are handy for sessions, password reset tokens and temporary logs.

Express and Node.js

Server-side questions.

Q15.What is Node.js and why is it good for APIs?

A JavaScript runtime built on V8 with a non-blocking, event-driven I/O model. A single thread can handle many concurrent connections while waiting on databases and networks, which suits I/O-heavy APIs.

Q16.Is Node.js single-threaded?

Your JavaScript runs on one main thread, but libuv uses a thread pool for some operations such as file system work, DNS lookups and crypto. CPU-heavy work should go to worker threads or another service.

Q17.What is middleware in Express?

A function with access to req, res and next that runs in order for matching routes. It is used for parsing bodies, logging, authentication, validation and error handling.

Q18.How do you handle errors in Express?

Use an error-handling middleware with four arguments (err, req, res, next) registered last. Express 5 passes rejected promises from async handlers to it automatically, so you no longer need wrapper functions.

Q19.How do you structure an Express project?

Separate routes, controllers, services and models, keep configuration in environment variables, validate input in middleware and keep business logic out of route files so it can be tested.

Q20.What is the difference between process.nextTick and setImmediate?

process.nextTick callbacks run right after the current operation, before promise microtasks and before the event loop continues. setImmediate runs in the check phase of the next loop iteration. Overusing nextTick can starve I/O.

Q21.What are streams in Node.js?

Objects for reading or writing data piece by piece, such as files or HTTP bodies. They keep memory low for large data and support backpressure. Use stream.pipeline to connect them safely.

Q22.How do you secure an Express API?

Use helmet for headers, configure CORS for known origins, validate input, rate limit, hash passwords with bcrypt or argon2, use parameterised queries and guard against NoSQL injection by rejecting operator keys like $gt in user input.

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

CommonJS uses require and module.exports and loads synchronously. ES modules use import and export, load asynchronously and are the standard. Set type module in package.json or use .mjs files. Recent Node versions can require ES modules in many cases.

Q24.How do you manage environment variables?

Read them from process.env, loaded from the host or a .env file in development with dotenv or Node's built-in --env-file flag. Validate them at startup and never commit secrets.

Q25.How do you scale a Node.js app?

Run several processes across CPU cores with PM2 or the cluster module, or several containers behind a load balancer. Keep the app stateless and store sessions and caches in Redis.

Q26.What is the difference between app.use and app.get?

app.use mounts middleware for all HTTP methods on a path prefix. app.get handles only GET requests on an exact route path.

Q27.How do you validate requests in Express?

With a schema library such as Zod, Joi or express-validator in a middleware before the controller. Return 400 or 422 with field errors and pass only validated data onward.

Q28.How do you log in a Node.js API?

Use a structured logger like pino or winston that writes JSON with a request ID, log level and context. Send logs to a central service and avoid logging passwords or tokens.

React for MERN

Frontend questions in a MERN context.

Q29.How does a React app talk to the Express API?

Through fetch or axios calls, usually wrapped in a data layer like TanStack Query or RTK Query. In development, a Vite proxy avoids CORS issues; in production, the API is on the same domain or CORS is configured.

Q30.How do you protect routes in React?

Wrap private routes in a component that checks the auth state and redirects to login. This only improves UX; the real protection must be on the API, which checks the token on every request.

Q31.Where should you store the JWT in a MERN app?

An HttpOnly, Secure, SameSite cookie is safer than localStorage because JavaScript cannot read it, which limits XSS damage. Use short-lived access tokens with a refresh token and CSRF protection for cookie-based auth.

Q32.How do you manage state in a MERN frontend?

Server data with TanStack Query or RTK Query, global client state like the current user or theme with Context, Zustand or Redux Toolkit, and local UI state with useState.

Q33.How do you handle forms and validation?

React Hook Form with a Zod schema on the client for instant feedback, and the same or a matching schema on the server, because client validation can be bypassed.

Q34.How do you upload files from React to Express?

Send a FormData object with the file, handle it in Express with multer or upload directly from the browser to cloud storage like S3 or Cloudinary with a signed URL. Store only the file URL in MongoDB.

Q35.How do you build the React app for production?

With Vite, which outputs static files. Serve them from a CDN or static host, or from Express with express.static and a fallback route for client-side routing.

Q36.What changes when you use Next.js instead of plain React in a MERN app?

Next.js adds routing, server rendering, server components and API routes, so some Express endpoints can move into the Next.js app. Many teams keep Express for a separate API used by mobile apps too.

Q37.How do you avoid useEffect fetch problems like race conditions?

Use a data library that handles caching and cancellation, or use an AbortController in the effect cleanup and ignore responses from old requests.

Q38.How do you handle environment variables in a Vite React app?

Only variables prefixed with VITE_ are exposed to the client through import.meta.env. Anything in the client bundle is public, so never put secrets there.

Authentication and full-stack scenarios

Putting the stack together.

Q39.Walk through a login flow in MERN.

React sends email and password to POST /api/auth/login. Express validates input, finds the user with Mongoose, compares the password hash with bcrypt, creates a JWT or session and sets it in an HttpOnly cookie. React then updates the auth state and redirects.

Q40.How do you implement refresh tokens?

Issue a short-lived access token and a longer-lived refresh token stored in an HttpOnly cookie and saved, hashed, in the database. When the access token expires, the client calls a refresh endpoint, which verifies, rotates the refresh token and returns a new access token.

Q41.How do you implement role-based access control?

Store roles on the user, include them in the token or load them per request, and write Express middleware like requireRole('admin'). Hide admin UI in React too, but rely on the server checks.

Q42.How would you add real-time features like chat or notifications?

Use Socket.IO or WebSockets on the Node server, authenticate the socket connection, use rooms per conversation, store messages in MongoDB and use a Redis adapter when running several server instances.

Q43.How do you deploy a MERN app?

MongoDB on Atlas, the Express API on a platform like Render, Railway, a VPS with PM2 and Nginx, or containers, and the React build on a static host or CDN. Set environment variables, HTTPS and CORS, and add CI to run tests on every push.

Q44.How do you search text in a MERN app?

For simple needs use a MongoDB text index. For relevance ranking, typo tolerance and autocomplete, use Atlas Search or a separate engine like Elasticsearch or Meilisearch.

Q45.A list page takes three seconds to load. Where do you look?

Check the network tab for the slow request, then the API: missing indexes in MongoDB, populate on large lists, no pagination or no projection. On the React side, check for repeated requests and re-renders.

Q46.How do you test a MERN application?

Unit test services with Jest or Vitest, test API routes with Supertest against an in-memory MongoDB or a test database, test React components with Testing Library and run end-to-end flows with Playwright or Cypress.

Q47.How do you prevent NoSQL injection?

Validate input types with a schema, reject objects where strings are expected, strip keys starting with $ or containing dots, and enable Mongoose's sanitizeFilter option or a sanitising middleware.

Q48.How would you handle a MongoDB schema change on a live app?

Make code accept both old and new shapes, write a migration script that updates documents in batches, run it, then remove support for the old shape. A schemaVersion field helps during the transition.

Q49.Why might CORS errors appear only in production?

The API's allowed origins do not include the production domain, credentials are sent without Access-Control-Allow-Credentials and a specific origin, or a proxy strips the headers. Configure the cors middleware with the exact frontend origin.

Q50.How do you handle file and image storage in production?

Store files in object storage such as S3, Cloudinary or similar, serve them through a CDN and save only URLs and metadata in MongoDB. Avoid storing large binaries in MongoDB documents.

Q51.What is the MERN request lifecycle from click to database and back?

A React event calls the API client, the browser sends an HTTP request with the cookie, Express middleware parses, authenticates and validates it, the controller calls a service that queries MongoDB through Mongoose, the JSON response returns and React updates state and re-renders.

How to prepare for the interview

  • Have a MERN project with authentication, CRUD, pagination and deployment that you can demo.
  • Be ready to design a Mongoose schema live and explain when you embed versus reference.
  • Know how you protect routes on both the Express side and the React side.
  • Expect a coding task: build an Express endpoint with validation and connect it to a React form.