MERN STACK
Mern Stack Interview Questions and Answers
SECTION 1: JavaScript & ES6+ Fundamentals (10 Questions)
-
What is the difference between let, const, and var?
-
var is function-scoped, hoisted with undefined.
-
let and const are block-scoped. let allows reassignment; const does not.
-
Use const by default, let when reassignment is required.
-
Explain closures in JavaScript.
A closure is when an inner function retains access to variables from its outer scope, even after the outer function has returned.
-
What are promises and async/await?
Promises represent a future value. async/await is syntactic sugar over Promises for better readability and error handling using try/catch.
-
What is the event loop in JavaScript?
It handles asynchronous operations via a queue and executes callbacks after the main call stack is empty.
-
Explain "this" keyword in JavaScript.
this refers to the context in which a function is executed: in global context it’s the window, in object methods it’s the object, in classes it’s the instance.
-
What is hoisting?
Variable and function declarations are moved to the top of their scope at runtime. Only declarations, not initializations, are hoisted.
-
Difference between == and ===?
== performs type coercion; === checks both value and type — prefer === for predictable behavior.
-
Explain destructuring in ES6.
Allows unpacking values from arrays or objects into distinct variables. Improves readability and reduces boilerplate.
-
What are arrow functions and their limitations?
Arrow functions do not bind their own this, arguments, or super. They’re great for inline callbacks, but avoid in object methods or constructors.
-
Explain the spread/rest operator.
-
Spread ... unpacks elements.
-
Rest ... collects remaining elements into an array.
SECTION 2: React.js (20 Questions)
-
What is React and why is it used?
React is a declarative, component-based UI library that improves performance using a virtual DOM and one-way data flow.
-
What are functional and class components?
-
Functional: Stateless, use useState, useEffect, etc.
-
Class: Use this.state, lifecycle methods. Functional components are preferred now with Hooks.
-
What are React Hooks?
Functions like useState, useEffect, useMemo that allow functional components to manage state and lifecycle behavior.
-
Explain the Virtual DOM.
It’s an in-memory representation of the real DOM. React updates only the parts that change, improving performance.
-
What is reconciliation in React?
The process of comparing the new virtual DOM with the previous one and updating the real DOM accordingly.
-
How does state differ from props?
-
State: Local and mutable.
-
Props: Read-only and passed from parent to child.
-
What is lifting state up?
Moving shared state to the closest common ancestor to manage it in one place.
-
Explain useEffect and its cleanup mechanism.
useEffect runs side effects. Cleanup is done via a return function to clear timers, listeners, etc.
-
What is useMemo vs useCallback?
-
useMemo: Caches computed values.
-
useCallback: Caches function references to prevent unnecessary re-renders.
-
Explain React Context API.
Allows global state management without prop drilling. Best for themes, auth, and user data.
-
What is Redux and how does it work with React?
Redux manages global state with a store, actions, and reducers. React components use useSelector and useDispatch.
-
What are Higher Order Components (HOCs)?
Functions that take a component and return an enhanced component — often used for cross-cutting concerns.
-
What is JSX?
JavaScript syntax extension that looks like HTML but transpiles to React.createElement.
-
How do you optimize performance in React apps?
Use React.memo, useMemo, lazy loading, code splitting, and avoid unnecessary re-renders.
-
What is React Router?
A routing library for SPA navigation. Components include <BrowserRouter>, <Route>, <Link>, and <Outlet>.
-
What is lazy loading and code splitting in React?
Dynamic imports (React.lazy) split large bundles into smaller ones, improving initial load performance.
-
What are controlled vs uncontrolled components?
-
Controlled: Form values managed via React state.
-
Uncontrolled: Use DOM directly via ref.
-
Explain React’s key prop and its importance.
Keys uniquely identify list elements; they help React in efficient re-rendering and reconciliation.
-
What is Prop Drilling and how to avoid it?
Passing props through intermediate components unnecessarily. Avoid it using Context or Redux.
-
What are error boundaries?
Class components with componentDidCatch and getDerivedStateFromError to catch runtime errors.
SECTION 3: Node.js & Express.js (20 Questions)
-
What is Node.js?
A JavaScript runtime built on Chrome’s V8, enabling server-side scripting using JS.
-
What is the Event Loop in Node.js?
Handles non-blocking I/O by offloading operations and executing callbacks via phases.
-
What is Express.js?
Minimal web framework for Node.js. Handles routing, middleware, and request-response logic.
-
How is middleware used in Express?
Functions with access to request, response, and next. Used for auth, logging, error handling.
-
What are streams in Node.js?
Interfaces for reading/writing data continuously — e.g., file reading, HTTP requests.
-
Explain process.nextTick vs setImmediate.
process.nextTick queues tasks before the event loop continues; setImmediate executes in the next event loop iteration.
-
What are common HTTP methods in REST APIs?
GET, POST, PUT, PATCH, DELETE — used for CRUD operations.
-
How to handle errors in Express?
Custom error-handling middleware (err, req, res, next) => {} at the end of routes.
-
What is CORS and how to enable it in Express?
Cross-Origin Resource Sharing — use cors package to allow cross-domain requests.
-
How to implement authentication in Express?
Use JWT tokens with middleware, or session-based using cookies and express-session.
-
What are environment variables and how to use them?
Store secrets/config in .env and access via process.env. Use dotenv package.
-
What is the role of package.json?
Metadata, dependencies, scripts, and configuration for the project.
-
How to create RESTful APIs with Express?
Define routes for each resource, use controllers/services, apply middleware, return JSON.
-
What are async/await pitfalls in Node?
Forgetting try/catch, or using await in non-async functions — leads to uncaught rejections.
-
Difference between require and import?
require: CommonJS (Node).
import: ES6 Modules (used with type: module or bundlers).
-
How to secure an Express app?
Sanitize inputs, use Helmet, rate limiting, HTTPS, JWT validation, and disable x-powered-by.
-
Explain request lifecycle in Express.
Client → Middleware chain → Route Handler → Response
-
How do you structure an Express project?
Use MVC: controllers, routes, models, services, middlewares. Use express.Router() for modular routing.
-
How to handle file uploads in Node.js?
Use multer middleware to handle multipart/form-data.
-
How to implement rate limiting?
Use packages like express-rate-limit to prevent abuse or DoS attacks.
SECTION 4: MongoDB (20 Questions)
-
What is MongoDB and why use it with MERN?
NoSQL database that stores documents in BSON format. Scalable, schema-less, flexible for JS-based stacks.
-
Difference between SQL and NoSQL?
-
SQL: Relational, fixed schema.
-
NoSQL: Document/key-value store, dynamic schema.
-
What is a document in MongoDB?
JSON-like structure with key-value pairs stored in collections. Similar to rows in SQL.
-
Explain CRUD operations in MongoDB.
-
Create: insertOne, insertMany
-
Read: find, findOne
-
Update: updateOne, updateMany
-
Delete: deleteOne, deleteMany
-
What are indexes in MongoDB?
Improve query performance. Types: single field, compound, text, geospatial.
-
How to model relationships in MongoDB?
-
Embedding (1:1, 1:many)
-
Referencing (many:many)
-
What is Mongoose?
ODM for MongoDB. Allows schema definition, validation, and model-based queries.
-
How to validate data in MongoDB?
Use Mongoose schemas with validation rules like required, enum, min, max, custom validators.
-
Explain aggregation in MongoDB.
Pipeline operations to transform data: $match, $group, $project, $sort, $lookup.
-
What is the difference between find and aggregate?
find is simple querying. aggregate is used for complex data transformations and computations.
-
How to handle transactions in MongoDB?
Use sessions with startTransaction, commitTransaction, and abortTransaction.
-
What is a replica set?
A group of MongoDB servers that maintain the same data for high availability.
-
Explain sharding in MongoDB.
Splits data across servers. Useful for horizontal scaling and managing large datasets.
-
What are schema design best practices?
Model based on access patterns, avoid deep nesting, index frequently queried fields.
-
What is the purpose of ObjectId?
Unique identifier for documents, 12-byte value that includes timestamp, machine, PID.
-
How do you prevent injection attacks in MongoDB?
Use parameterized queries, input validation, and ORM-level protections (e.g., Mongoose).
-
How to paginate results in MongoDB?
Use .skip() and .limit() or use range-based pagination for performance.
-
How do you back up and restore MongoDB data?
Use mongodump and mongorestore or Atlas backup features.
-
What is the purpose of $lookup in aggregation?
Joins collections, similar to SQL JOINs, for relational-like querying.
-
What is TTL Index in MongoDB?
Auto-deletes documents after a certain period using a timestamp field.
SECTION 5: DevOps, Testing, and Deployment (15 Questions)
-
How to deploy a MERN stack app to production?
-
Backend: Host on Heroku/Vercel/Render.
-
Frontend: Netlify/Vercel
-
MongoDB: Atlas
-
Use environment variables, SSL, and CI/CD pipelines.
-
How to handle environment variables securely?
Store them in .env, never commit to Git. Use dotenv to load in code.
-
What is the use of PM2 in Node.js?
Process manager to keep apps alive, manage logs, and enable clustering.
-
What is the importance of logging and how to implement it?
Use tools like winston, morgan, or ELK stack to trace issues and monitor performance.
-
How do you test your MERN app?
-
Backend: Jest, Supertest
-
Frontend: React Testing Library, Jest
-
E2E: Cypress
-
What is CI/CD and how do you use it?
Automate building, testing, and deploying apps using GitHub Actions, GitLab CI, Jenkins, etc.
-
How do you dockerize a MERN app?
Use Dockerfiles and Docker Compose to containerize services. Split MongoDB, backend, frontend.
-
How do you monitor and scale a Node.js application?
Use tools like New Relic, PM2, or Datadog. Use load balancing and auto-scaling with Nginx and cloud platforms.
-
What is reverse proxy and why use it?
A server (like Nginx) that forwards requests to backend servers. Adds caching, SSL, and load balancing.
-
How do you handle CORS in production?
Whitelist domains in middleware and configure headers properly to avoid security risks.
-
How to handle database migrations in MongoDB?
Use migrate-mongo, custom scripts, or version-controlled migration tools.
-
How to implement caching in MERN apps?
Use Redis for server-side caching and HTTP cache headers for frontend performance.
-
What are security best practices in MERN stack?
Input validation, helmet, CORS, HTTPS, avoid eval, secure auth, and sanitize queries.
-
How do you manage secrets in production?
Use Vaults, environment variables, or platform-specific secret managers (e.g., AWS Secrets Manager).
-
How do you perform load testing on your APIs?
Use tools like Apache JMeter, Artillery, or k6 to simulate concurrent users and measure performance.
SECTION 6: Scenario-Based & System Design (15 Questions)
-
How would you design a scalable authentication system?
Use JWT tokens, refresh tokens, OAuth, rate-limiting, RBAC, and store sessions securely.
-
How do you optimize a slow MongoDB query?
Use indexes, avoid $regex on large fields, project only required fields, analyze with .explain().
-
How would you build a real-time chat app using MERN?
Use Socket.IO for real-time messaging, MongoDB for storing messages, React for UI, Node/Express for APIs.
-
How would you structure a large MERN project?
Use domain-based folder structure, modular services, controllers, and shared utils. Follow separation of concerns.
-
How to handle file storage in MERN apps?
Use AWS S3 or Cloudinary for storage. Upload via frontend, backend handles credentials and uploads.
-
How do you handle rate limiting and abuse prevention?
Use express-rate-limit, IP throttling, and CAPTCHA.
-
How would you implement multi-role authorization?
Add roles to user schema, check permissions in middleware before handling requests.
-
How do you keep frontend and backend in sync?
Use OpenAPI/Swagger, TypeScript shared types, and contracts. Maintain API versioning.
-
How to make a MERN app SEO-friendly?
Use SSR frameworks like Next.js or pre-rendering techniques.
-
How do you implement infinite scroll in React with MongoDB?
Backend supports pagination via skip/limit or cursor. Frontend fetches on scroll event.
-
What design patterns have you used in MERN apps?
MVC, Singleton (DB connection), Factory (service creation), Observer (WebSockets), Strategy (auth).
-
How to debug memory leaks in a Node app?
Use --inspect, heap snapshots, clinic.js, or Chrome DevTools for server.
-
How do you handle rollback on deployment failure?
Use blue-green or canary deployments. Maintain backup builds or snapshots.
-
How do you ensure code quality in a team?
Enforce linting, Prettier, unit tests, PR reviews, CI pipelines.
-
How do you handle breaking changes in APIs?
Use API versioning (/v1, /v2), backward compatibility, deprecation notices.
What is the difference between let, const, and var?
-
varis function-scoped, hoisted withundefined. -
letandconstare block-scoped.letallows reassignment;constdoes not. -
Use
constby default,letwhen reassignment is required.
Explain closures in JavaScript.
A closure is when an inner function retains access to variables from its outer scope, even after the outer function has returned.
What are promises and async/await?
Promises represent a future value. async/await is syntactic sugar over Promises for better readability and error handling using try/catch.
What is the event loop in JavaScript?
It handles asynchronous operations via a queue and executes callbacks after the main call stack is empty.
Explain "this" keyword in JavaScript.
this refers to the context in which a function is executed: in global context it’s the window, in object methods it’s the object, in classes it’s the instance.
What is hoisting?
Variable and function declarations are moved to the top of their scope at runtime. Only declarations, not initializations, are hoisted.
Difference between == and ===?
== performs type coercion; === checks both value and type — prefer === for predictable behavior.
Explain destructuring in ES6.
Allows unpacking values from arrays or objects into distinct variables. Improves readability and reduces boilerplate.
What are arrow functions and their limitations?
Arrow functions do not bind their own this, arguments, or super. They’re great for inline callbacks, but avoid in object methods or constructors.
Explain the spread/rest operator.
Spread ... unpacks elements.
Rest ... collects remaining elements into an array.
What is React and why is it used?
React is a declarative, component-based UI library that improves performance using a virtual DOM and one-way data flow.
What are functional and class components?
Functional: Stateless, use useState, useEffect, etc.
Class: Use this.state, lifecycle methods. Functional components are preferred now with Hooks.
What are React Hooks?
Functions like useState, useEffect, useMemo that allow functional components to manage state and lifecycle behavior.
Explain the Virtual DOM.
It’s an in-memory representation of the real DOM. React updates only the parts that change, improving performance.
What is reconciliation in React?
The process of comparing the new virtual DOM with the previous one and updating the real DOM accordingly.
How does state differ from props?
State: Local and mutable.
Props: Read-only and passed from parent to child.
What is lifting state up?
Moving shared state to the closest common ancestor to manage it in one place.
Explain useEffect and its cleanup mechanism.
useEffect runs side effects. Cleanup is done via a return function to clear timers, listeners, etc.
What is useMemo vs useCallback?
useMemo: Caches computed values.
useCallback: Caches function references to prevent unnecessary re-renders.
Explain React Context API.
Allows global state management without prop drilling. Best for themes, auth, and user data.
What is Redux and how does it work with React?
Redux manages global state with a store, actions, and reducers. React components use useSelector and useDispatch.
What are Higher Order Components (HOCs)?
Functions that take a component and return an enhanced component — often used for cross-cutting concerns.
What is JSX?
JavaScript syntax extension that looks like HTML but transpiles to React.createElement.
How do you optimize performance in React apps?
Use React.memo, useMemo, lazy loading, code splitting, and avoid unnecessary re-renders.
What is React Router?
A routing library for SPA navigation. Components include <BrowserRouter>, <Route>, <Link>, and <Outlet>.
What is lazy loading and code splitting in React?
Dynamic imports (React.lazy) split large bundles into smaller ones, improving initial load performance.
What are controlled vs uncontrolled components?
Controlled: Form values managed via React state.
Uncontrolled: Use DOM directly via ref.
Explain React’s key prop and its importance.
Keys uniquely identify list elements; they help React in efficient re-rendering and reconciliation.
What is Prop Drilling and how to avoid it?
Passing props through intermediate components unnecessarily. Avoid it using Context or Redux.
What are error boundaries?
Class components with componentDidCatch and getDerivedStateFromError to catch runtime errors.
What is Node.js?
A JavaScript runtime built on Chrome’s V8, enabling server-side scripting using JS.
What is the Event Loop in Node.js?
Handles non-blocking I/O by offloading operations and executing callbacks via phases.
What is Express.js?
Minimal web framework for Node.js. Handles routing, middleware, and request-response logic.
How is middleware used in Express?
Functions with access to request, response, and next. Used for auth, logging, error handling.
What are streams in Node.js?
Interfaces for reading/writing data continuously — e.g., file reading, HTTP requests.
Explain process.nextTick vs setImmediate.
process.nextTick queues tasks before the event loop continues; setImmediate executes in the next event loop iteration.
What are common HTTP methods in REST APIs?
GET, POST, PUT, PATCH, DELETE — used for CRUD operations.
How to handle errors in Express?
Custom error-handling middleware (err, req, res, next) => {} at the end of routes.
What is CORS and how to enable it in Express?
Cross-Origin Resource Sharing — use cors package to allow cross-domain requests.
How to implement authentication in Express?
Use JWT tokens with middleware, or session-based using cookies and express-session.
What are environment variables and how to use them?
Store secrets/config in .env and access via process.env. Use dotenv package.
What is the role of package.json?
Metadata, dependencies, scripts, and configuration for the project.
How to create RESTful APIs with Express?
Define routes for each resource, use controllers/services, apply middleware, return JSON.
What are async/await pitfalls in Node?
Forgetting try/catch, or using await in non-async functions — leads to uncaught rejections.
Difference between require and import?
require: CommonJS (Node).
import: ES6 Modules (used with type: module or bundlers).
How to secure an Express app?
Sanitize inputs, use Helmet, rate limiting, HTTPS, JWT validation, and disable x-powered-by.
Explain request lifecycle in Express.
Client → Middleware chain → Route Handler → Response
How do you structure an Express project?
Use MVC: controllers, routes, models, services, middlewares. Use express.Router() for modular routing.
How to handle file uploads in Node.js?
Use multer middleware to handle multipart/form-data.
How to implement rate limiting?
Use packages like express-rate-limit to prevent abuse or DoS attacks.
What is MongoDB and why use it with MERN?
NoSQL database that stores documents in BSON format. Scalable, schema-less, flexible for JS-based stacks.
Difference between SQL and NoSQL?
SQL: Relational, fixed schema.
NoSQL: Document/key-value store, dynamic schema.
What is a document in MongoDB?
JSON-like structure with key-value pairs stored in collections. Similar to rows in SQL.
Explain CRUD operations in MongoDB.
Create: insertOne, insertMany
Read: find, findOne
Update: updateOne, updateMany
Delete: deleteOne, deleteMany
What are indexes in MongoDB?
Improve query performance. Types: single field, compound, text, geospatial.
How to model relationships in MongoDB?
Embedding (1:1, 1:many)
Referencing (many:many)
What is Mongoose?
ODM for MongoDB. Allows schema definition, validation, and model-based queries.
How to validate data in MongoDB?
Use Mongoose schemas with validation rules like required, enum, min, max, custom validators.
Explain aggregation in MongoDB.
Pipeline operations to transform data: $match, $group, $project, $sort, $lookup.
What is the difference between find and aggregate?
find is simple querying. aggregate is used for complex data transformations and computations.
How to handle transactions in MongoDB?
Use sessions with startTransaction, commitTransaction, and abortTransaction.
What is a replica set?
A group of MongoDB servers that maintain the same data for high availability.
Explain sharding in MongoDB.
Splits data across servers. Useful for horizontal scaling and managing large datasets.
What are schema design best practices?
Model based on access patterns, avoid deep nesting, index frequently queried fields.
What is the purpose of ObjectId?
Unique identifier for documents, 12-byte value that includes timestamp, machine, PID.
How do you prevent injection attacks in MongoDB?
Use parameterized queries, input validation, and ORM-level protections (e.g., Mongoose).
How to paginate results in MongoDB?
Use .skip() and .limit() or use range-based pagination for performance.
How do you back up and restore MongoDB data?
Use mongodump and mongorestore or Atlas backup features.
What is the purpose of $lookup in aggregation?
Joins collections, similar to SQL JOINs, for relational-like querying.
What is TTL Index in MongoDB?
Auto-deletes documents after a certain period using a timestamp field.
How to deploy a MERN stack app to production?
Backend: Host on Heroku/Vercel/Render.
Frontend: Netlify/Vercel
MongoDB: Atlas
Use environment variables, SSL, and CI/CD pipelines.
How to handle environment variables securely?
Store them in .env, never commit to Git. Use dotenv to load in code.
What is the use of PM2 in Node.js?
Process manager to keep apps alive, manage logs, and enable clustering.
What is the importance of logging and how to implement it?
Use tools like winston, morgan, or ELK stack to trace issues and monitor performance.
How do you test your MERN app?
Backend: Jest, Supertest
Frontend: React Testing Library, Jest
E2E: Cypress
What is CI/CD and how do you use it?
Automate building, testing, and deploying apps using GitHub Actions, GitLab CI, Jenkins, etc.
How do you dockerize a MERN app?
Use Dockerfiles and Docker Compose to containerize services. Split MongoDB, backend, frontend.
How do you monitor and scale a Node.js application?
Use tools like New Relic, PM2, or Datadog. Use load balancing and auto-scaling with Nginx and cloud platforms.
What is reverse proxy and why use it?
A server (like Nginx) that forwards requests to backend servers. Adds caching, SSL, and load balancing.
How do you handle CORS in production?
Whitelist domains in middleware and configure headers properly to avoid security risks.
How to handle database migrations in MongoDB?
Use migrate-mongo, custom scripts, or version-controlled migration tools.
How to implement caching in MERN apps?
Use Redis for server-side caching and HTTP cache headers for frontend performance.
What are security best practices in MERN stack?
Input validation, helmet, CORS, HTTPS, avoid eval, secure auth, and sanitize queries.
How do you manage secrets in production?
Use Vaults, environment variables, or platform-specific secret managers (e.g., AWS Secrets Manager).
How do you perform load testing on your APIs?
Use tools like Apache JMeter, Artillery, or k6 to simulate concurrent users and measure performance.
How would you design a scalable authentication system?
Use JWT tokens, refresh tokens, OAuth, rate-limiting, RBAC, and store sessions securely.
How do you optimize a slow MongoDB query?
Use indexes, avoid $regex on large fields, project only required fields, analyze with .explain().
How would you build a real-time chat app using MERN?
Use Socket.IO for real-time messaging, MongoDB for storing messages, React for UI, Node/Express for APIs.
How would you structure a large MERN project?
Use domain-based folder structure, modular services, controllers, and shared utils. Follow separation of concerns.
How to handle file storage in MERN apps?
Use AWS S3 or Cloudinary for storage. Upload via frontend, backend handles credentials and uploads.
How do you handle rate limiting and abuse prevention?
Use express-rate-limit, IP throttling, and CAPTCHA.
How would you implement multi-role authorization?
Add roles to user schema, check permissions in middleware before handling requests.
How do you keep frontend and backend in sync?
Use OpenAPI/Swagger, TypeScript shared types, and contracts. Maintain API versioning.
How to make a MERN app SEO-friendly?
Use SSR frameworks like Next.js or pre-rendering techniques.
How do you implement infinite scroll in React with MongoDB?
Backend supports pagination via skip/limit or cursor. Frontend fetches on scroll event.
What design patterns have you used in MERN apps?
MVC, Singleton (DB connection), Factory (service creation), Observer (WebSockets), Strategy (auth).
How to debug memory leaks in a Node app?
Use --inspect, heap snapshots, clinic.js, or Chrome DevTools for server.
How do you handle rollback on deployment failure?
Use blue-green or canary deployments. Maintain backup builds or snapshots.
How do you ensure code quality in a team?
Enforce linting, Prettier, unit tests, PR reviews, CI pipelines.
How do you handle breaking changes in APIs?
Use API versioning (/v1, /v2), backward compatibility, deprecation notices.