MERN Stack Interview Questions 2025

Top 100 MERN Stack Interview Questions 2025

Are you gearing up for a MERN Stack interview in 2025? You’re in the right place! The MERN stack—MongoDB, Express.js, React.js, and Node.js—has become a favorite for building modern, dynamic web applications. Companies are always on the lookout for skilled MERN developers who can create amazing projects and solve real-world problems.

This blog is here to help you ace your interview! We’ve compiled 100 of the most important MERN Stack interview questions, updated for 2025 trends. Whether you’re a beginner trying to land your first job or an experienced developer brushing up your skills, this guide covers you.

What is the MERN Stack?

The MERN Stack is a popular set of technologies used to build modern web applications. It’s named after its four core components:

  • MongoDB
    • A NoSQL database where you store your app’s data in the form of flexible, JSON-like documents. It’s great for handling large volumes of unstructured data.
  • Express.js
    • A lightweight framework for building the backend of your application. It simplifies handling server logic, routing, and API development.
  • React.js
    • A powerful JavaScript library for creating user interfaces. It’s what users see and interact with, making it perfect for building fast, dynamic, and responsive web pages.
  • Node.js
    • A runtime environment that allows you to run JavaScript on the server side. It enables you to build scalable, high-performance backend systems.

How They Work Together:

The MERN stack covers both the frontend (React) and backend (Node.js, Express), with MongoDB managing the data. For example:

  • React creates the user interface.
  • Node.js and Express handle server requests.
  • MongoDB stores and retrieves the app’s data.

Everything uses JavaScript, making development faster and more seamless.

Why Choose the MERN Stack?

  • It’s Full-Stack JavaScript
    • MERN lets you use JavaScript for the frontend, backend, and database operations. This means you only need to master one language to work across the entire stack.
  • Highly Scalable and Flexible
    • MongoDB’s document structure and Node.js’s non-blocking architecture make MERN ideal for apps that need to scale with growing users or features.
  • Great Performance
    • React makes apps super fast on the frontend, while Node.js ensures high performance on the backend.
  • Massive Community Support
    • The MERN stack has a huge community of developers, so finding resources, libraries, and help is easy.

How Does MERN Compare to Other Stacks?

  • MEAN Stack: Similar to MERN, but uses Angular instead of React. Angular is great for large-scale enterprise apps, while React is preferred for flexibility and a faster learning curve.
  • LAMP Stack: Based on PHP, MySQL, and Apache. It’s great for traditional applications but less modern and scalable than MERN.

In short, the MERN stack is a go-to choice for building cutting-edge web apps, especially when speed, scalability, and a JavaScript-first approach are priorities. Let’s move straightaway to the questions and prepare you for the interview.

What is the difference between var, let, and const?

  • var: Function-scoped, can be redeclared.
  • let: Block-scoped, cannot be redeclared within the same scope.
  • const: Block-scoped, used for constants, cannot be reassigned.

Explain the concept of closures in JavaScript.

A closure is a function that remembers the variables from its outer scope, even after the outer function has executed.

What is the purpose of promises in JavaScript?

Promises handle asynchronous operations by allowing you to attach success (.then) and failure (.catch) handlers to the operation.

What is the difference between == and === in JavaScript?

  • ==: Compares values, allowing type coercion.
  • ===: Strict equality, compares both value and type.

Explain event bubbling and event capturing.

  • Event Bubbling: The event propagates from the target element up to its parent elements.
  • Event Capturing: The event propagates from the parent elements down to the target.

What is MongoDB?

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents.

How do you insert a document into a MongoDB collection?

Using db.collection.insertOne({key: value}).

What is the difference between find() and findOne() in MongoDB?

  • find(): Retrieves all matching documents.
  • findOne(): Retrieves the first matching document.

How do you update a document in MongoDB?

Using db.collection.updateOne({filter}, {$set: {key: value}}).

What is indexing in MongoDB?

Indexing improves query performance by creating a data structure that stores field values for quick lookups.

What is middleware in Express.js?

Middleware functions handle requests and responses and can perform tasks like logging, authentication, or error handling.

How do you define a route in Express.js?

Example:

app.get(‘/route’, (req, res) => res.send(‘Hello, World!’));

What is the purpose of next() in Express middleware?

next() passes control to the next middleware function in the stack.

How do you handle errors in Express.js?

Using error-handling middleware:

app.use((err, req, res, next) => {

  res.status(500).send(err.message);

});

What is the difference between app.use() and app.get()?

  • app.use(): Attaches middleware for any HTTP method.
  • app.get(): Specifically handles GET requests.

What is JSX in React?

JSX stands for JavaScript XML and allows you to write HTML-like syntax in JavaScript files.

What are functional components in React?

Simple JavaScript functions that return JSX. Example:

const Component = () => <h1>Hello</h1>;

What is the difference between props and state in React?

Props: Read-only, passed from parent to child components.

State: Managed within the component, can change over time.

What is the purpose of the useState hook?

It allows you to add state to functional components. Example:

const [count, setCount] = useState(0);

How do you handle events in React?

Example:

const handleClick = () => console.log(‘Clicked’);

<button onClick={handleClick}>Click Me</button>

What is Node.js?

A JavaScript runtime built on Chrome’s V8 engine, used for building scalable server-side applications.

Explain the event loop in Node.js.

The event loop handles asynchronous operations by processing callbacks in different phases (e.g., timers, IO).

What is a callback function in Node.js?

A function passed as an argument to another function, executed after the completion of an operation.

How do you export and import modules in Node.js?

  • Export: module.exports = someFunction;
  • Import: const someFunction = require(‘./module’);

What is the purpose of the fs module in Node.js?

To handle file system operations like reading, writing, and deleting files.

How do you read a file in Node.js?

Example:

const fs = require(‘fs’);

fs.readFile(‘file.txt’, ‘utf8’, (err, data) => {

  if (err) console.error(err);

  else console.log(data);

});

What is the difference between process.nextTick() and setImmediate() in Node.js?

  • process.nextTick(): Executes callbacks before the event loop continues.
  • setImmediate(): Executes callbacks in the next iteration of the event loop.

How do you create a simple HTTP server in Node.js?

Example:

const http = require(‘http’);

const server = http.createServer((req, res) => {

  res.end(‘Hello, World!’);

});

server.listen(3000);

What is the purpose of the package.json file?

It holds metadata for the project, including dependencies, scripts, and version information.

What is the difference between require() and import?

  • require(): CommonJS module system, used in Node.js.
  • import: ES6 module system, used in modern JavaScript.

What is indexing in MongoDB, and why is it important?

Indexing improves query performance by creating a data structure for quick lookups. Example:

db.collection.createIndex({ field: 1 });

How do you create a compound index in MongoDB?

A compound index includes multiple fields:

db.collection.createIndex({ field1: 1, field2: -1 });

What is an aggregation pipeline in MongoDB?

A series of stages (e.g., $match, $group, $sort) that process documents and transform data.

How do you use the $match stage in aggregation?

Filters documents by a condition:

db.collection.aggregate([{ $match: { field: value } }]);

How does MongoDB handle relationships between collections?

MongoDB supports two approaches:

  • Embedding: Store related data within a single document.
  • Referencing: Use ObjectId references to link documents in different collections.

What is sharding in MongoDB?

Sharding distributes data across multiple servers to handle large datasets and ensure high availability.

What is a replica set in MongoDB?

A group of MongoDB servers that maintain the same dataset for redundancy and failover.

How do you perform text search in MongoDB?

Use text indexes:

db.collection.createIndex({ field: ‘text’ });

db.collection.find({ $text: { $search: ‘keyword’ } });

What is the difference between $project and $addFields in MongoDB aggregation?

  • $project: Shapes the output documents by selecting fields.
  • $addFields: Adds or modifies fields in the output.

How do you handle pagination in MongoDB?

Use limit and skip:

db.collection.find().skip(10).limit(10);

How do you handle errors globally in Express.js?

Use an error-handling middleware:

app.use((err, req, res, next) => {

  res.status(500).json({ error: err.message });

});

How do you define a route parameter in Express.js?

Example:

app.get(‘/user/:id’, (req, res) => {

  res.send(req.params.id);

});

What is the purpose of res.locals in Express.js?

res.locals is an object used to pass data between middleware and routes.

How do you validate data in Express.js?

Use libraries like Joi or express-validator.

What is the difference between res.json() and res.send()?

res.json(): Automatically converts objects to JSON format.

res.send(): Sends various types of responses (HTML, text, JSON).

How do you use app.all() in Express.js?

It matches all HTTP methods for a specific route. Example:

app.all(‘/route’, (req, res) => res.send(‘Matches all methods’));

What is the helmet middleware used for in Express.js?

Helmet adds security headers to your Express app to protect against vulnerabilities.

How do you define a middleware that runs for all routes?

Use app.use():

app.use((req, res, next) => {

  console.log(‘Middleware’);

  next();

});

How do you send a file as a response in Express.js?

Example:

res.sendFile(‘path/to/file’);

What is the difference between app.listen() and server.listen()?

  • app.listen() is a wrapper around server.listen() and is specific to Express.js.

What is the useEffect hook used for in React?

It performs side effects like data fetching, subscriptions, or DOM manipulation.

How does the Context API work in React?

It provides a way to pass data through the component tree without prop drilling. Example:

const MyContext = React.createContext();

How do you memoize a component in React?

Use React.memo to prevent unnecessary re-renders.

What is the difference between useState and useReducer in React?

useState: Simplifies state management for simple updates.

useReducer: Manages complex state logic.

How do you optimize React performance?

Use techniques like:

  • Memoization (React.memo, useMemo, useCallback).
  • Lazy loading with React.lazy.
  • Code splitting.

What is server-side rendering (SSR) in React?

SSR generates HTML on the server before sending it to the client for faster initial load and better SEO.

What is the purpose of the useRef hook?

It holds mutable values without causing re-renders, often used to reference DOM elements.

How do you handle error boundaries in React?

Create a class component with componentDidCatch and getDerivedStateFromError methods.

What are React fragments?

A way to group multiple elements without adding extra nodes to the DOM. Example:

<React.Fragment></React.Fragment>

What is react-query, and how is it used?

react-query simplifies data fetching and caching in React applications.

What are streams in Node.js?

Streams allow reading or writing data in chunks instead of loading the entire data into memory.

What are the different types of streams in Node.js?

Readable, Writable, Duplex, and Transform streams.

How do you create a readable stream in Node.js?

Example:

const fs = require(‘fs’);

const stream = fs.createReadStream(‘file.txt’);

What is the pipe() method in Node.js?

It connects readable streams to writable streams. Example:

readableStream.pipe(writableStream);

What is the cluster module in Node.js?

It enables the creation of multiple processes that share the same server port to improve performance.

How do you use the cluster module?

Example:

const cluster = require(‘cluster’);

if (cluster.isMaster) {

  cluster.fork();

} else {

  // Worker process code

}

What is the purpose of the os module in Node.js?

Provides operating system-related utility methods.

How do you handle backpressure in Node.js streams?

Use the drain event and pause()/resume() methods to manage data flow.

What is the difference between synchronous and asynchronous methods in Node.js?

  • Synchronous methods block execution until completion.
  • Asynchronous methods use callbacks or promises to avoid blocking.

How do you handle unhandled rejections in Node.js?

Use the process.on(‘unhandledRejection’) event.

What is sharding in MongoDB, and why is it important?

Sharding is the process of distributing data across multiple servers to ensure scalability and high availability for large datasets. Example:

sh.enableSharding(“database_name”);

How do you choose a shard key in MongoDB?

A good shard key should have high cardinality, be evenly distributed, and match query patterns.

What is replication in MongoDB?

Replication creates multiple copies of data across servers to provide redundancy and failover support.

How does MongoDB handle failover in a replica set?

If the primary node goes down, a secondary node is automatically promoted to primary using an election process.

Describe the CAP theorem and how MongoDB implements it.

The CAP theorem states that a distributed system can guarantee only two of the following three: Consistency, Availability, and Partition tolerance.

MongoDB prioritizes availability and partition tolerance but provides tunable consistency options.

How do you design an efficient schema in MongoDB?

Use denormalization to store related data together.

Avoid joins by embedding documents where appropriate.

Use references for large, complex relationships.

What is the difference between a primary and secondary index in MongoDB?

Primary index: Automatically created for the _id field.

Secondary index: Custom indexes on other fields for faster queries.

How does MongoDB ensure ACID compliance for transactions?

Starting with version 4.0, MongoDB supports multi-document ACID transactions for replica sets.

How would you secure an Express.js application?

  • Use helmet for security headers.
  • Validate and sanitize user input to prevent injection attacks.
  • Implement rate limiting to prevent DDoS attacks.
  • Use HTTPS and secure cookies.

How do you implement authentication in Express.js?

Use libraries like passport.js or jsonwebtoken for authentication and session management.

What is CORS, and how do you enable it in Express.js?

CORS (Cross-Origin Resource Sharing) allows restricted resources to be accessed from different domains. Example:

const cors = require(‘cors’);

app.use(cors());

How do you implement role-based access control in Express.js?

Example:

const authorize = (roles) => (req, res, next) => {

  if (!roles.includes(req.user.role)) return res.status(403).send(‘Forbidden’);

  next();

};

app.get(‘/admin’, authorize([‘admin’]), (req, res) => res.send(‘Admin’));

How do you define nested routing in Express.js?

Example:

const router = express.Router();

router.get(‘/subroute’, (req, res) => res.send(‘Nested Route’));

app.use(‘/mainroute’, router);

What is Redux, and why is it used?

Redux is a state management library that centralizes app state, making it easier to manage complex state across components.

What are the core concepts of Redux?

Store: Holds the state.

Actions: Plain JavaScript objects describing changes.

Reducers: Functions that specify how the state changes.

How do you implement server-side rendering (SSR) with Next.js?

Next.js pre-renders pages on the server for better SEO and faster load times. Example:

export async function getServerSideProps() {

  const data = await fetch(‘api/data’);

  return { props: { data } };

}

Explain the difference between server-side rendering and client-side rendering in React.

Client-Side Rendering: HTML is generated on the client after downloading JavaScript.

Server-Side Rendering: HTML is pre-rendered on the server and sent to the client, improving initial load time and SEO.

How do you optimize Redux performance?

Use reselect for memoized selectors.

Normalize state shape.

Avoid unnecessary re-renders by splitting state and using connect.

What is code-splitting in React, and how does Next.js handle it?

Code-splitting divides the app into smaller chunks to load resources only when needed.

Next.js automatically code-splits pages and components to optimize performance.

How do you optimize a Node.js application for performance?

  • Use clustering to utilize multiple CPU cores.
  • Enable gzip compression for responses.
  • Use caching (e.g., Redis) to store frequently used data.
  • Avoid blocking the event loop with heavy computations.

What is the cluster module in Node.js, and how does it improve performance?

The cluster module allows creating multiple Node.js processes to handle requests in parallel. Example:

const cluster = require(‘cluster’);

if (cluster.isMaster) {

  cluster.fork();

} else {

  // Worker process logic

}

How do you implement microservices with Node.js?

Break the app into small, independent services communicating via APIs or message queues like RabbitMQ or Kafka.

What is the role of Docker in microservices architecture?

Docker containerizes services, ensuring consistency across environments and simplifying deployment.

How do you handle inter-service communication in microservices?

Use REST APIs, gRPC, or message queues for communication between services.

What is the worker_threads module in Node.js?

It allows running JavaScript code in parallel threads. Example:

const { Worker } = require(‘worker_threads’);

new Worker(‘./worker.js’);

1. Create a Simple CRUD App with Express.js and MongoDB

Challenge:
Write a REST API in Express.js that supports CRUD operations for a products collection in MongoDB.

Solution:

const express = require(‘express’);

const mongoose = require(‘mongoose’);

const app = express();

// Connect to MongoDB

mongoose.connect(‘mongodb://localhost:27017/productsDB’, { useNewUrlParser: true, useUnifiedTopology: true });

// Define a Mongoose schema

const productSchema = new mongoose.Schema({

  name: String,

  price: Number,

  description: String,

});

const Product = mongoose.model(‘Product’, productSchema);

app.use(express.json());

// Create

app.post(‘/products’, async (req, res) => {

  const product = new Product(req.body);

  await product.save();

  res.status(201).send(product);

});

// Read

app.get(‘/products’, async (req, res) => {

  const products = await Product.find();

  res.send(products);

});

// Update

app.put(‘/products/:id’, async (req, res) => {

  const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });

  res.send(product);

});

// Delete

app.delete(‘/products/:id’, async (req, res) => {

  await Product.findByIdAndDelete(req.params.id);

  res.send({ message: ‘Product deleted’ });

});

app.listen(3000, () => console.log(‘Server running on port 3000’));

2. Optimize a React App for Performance

Challenge:
Given a React component that re-renders unnecessarily, optimize it using React.memo and useCallback.

Problem Component:

function Counter({ count, onIncrement }) {

  console.log(‘Counter rendered’);

  return <button onClick={onIncrement}>Count: {count}</button>;

}

export default function App() {

  const [count, setCount] = React.useState(0);

  return <Counter count={count} onIncrement={() => setCount(count + 1)} />;

}

Solution:

import React from ‘react’;

const Counter = React.memo(({ count, onIncrement }) => {

  console.log(‘Counter rendered’);

  return <button onClick={onIncrement}>Count: {count}</button>;

});

export default function App() {

  const [count, setCount] = React.useState(0);

  const handleIncrement = React.useCallback(() => setCount((c) => c + 1), []);

  return <Counter count={count} onIncrement={handleIncrement} />;

}

3. Implement User Authentication with JWT in Node.js

Challenge:
Write a function in Express.js that generates a JWT token upon successful login.

Solution:

const express = require(‘express’);

const jwt = require(‘jsonwebtoken’);

const app = express();

const SECRET_KEY = ‘your_secret_key’;

// Mock user

const user = { username: ‘test’, password: ‘password’ };

app.use(express.json());

// Login endpoint

app.post(‘/login’, (req, res) => {

  const { username, password } = req.body;

  if (username === user.username && password === user.password) {

    const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: ‘1h’ });

    res.send({ token });

  } else {

    res.status(401).send({ message: ‘Invalid credentials’ });

  }

});

// Protected route

app.get(‘/protected’, (req, res) => {

  const token = req.headers[‘authorization’];

  try {

    const decoded = jwt.verify(token, SECRET_KEY);

    res.send({ message: ‘Welcome!’, user: decoded });

  } catch (err) {

    res.status(401).send({ message: ‘Unauthorized’ });

  }

});

app.listen(3000, () => console.log(‘Server running on port 3000’));

4. Create a Pagination API in MongoDB

Challenge:
Write an API that fetches paginated results from a users collection in MongoDB.

Solution:

app.get(‘/users’, async (req, res) => {

  const { page = 1, limit = 10 } = req.query;

  const users = await User.find()

    .skip((page – 1) * limit)

    .limit(Number(limit));

  res.send(users);

});

5. Build a Simple React Context for Theme Management

Challenge:
Create a React app where users can toggle between light and dark themes using the Context API.

Solution:

import React, { createContext, useContext, useState } from ‘react’;

const ThemeContext = createContext();

function ThemeProvider({ children }) {

  const [theme, setTheme] = useState(‘light’);

  const toggleTheme = () => setTheme((prev) => (prev === ‘light’ ? ‘dark’ : ‘light’));

  return (

    <ThemeContext.Provider value={{ theme, toggleTheme }}>

      {children}

    </ThemeContext.Provider>

  );

}

function ThemeButton() {

  const { theme, toggleTheme } = useContext(ThemeContext);

  return <button onClick={toggleTheme}>Current Theme: {theme}</button>;

}

export default function App() {

  return (

    <ThemeProvider>

      <ThemeButton />

    </ThemeProvider>

  );

}

These coding challenges test real-world problem-solving skills in MERN, covering CRUD operations, optimisation, authentication, pagination, and state management.

Trending topics in MERN

As we approach 2025, the MERN stack—comprising MongoDB, Express.js, React.js, and Node.js—continues to evolve, introducing new features and best practices. Here’s a look at some of the latest trends:

1. React Server Components

React Server Components (RSCs) are a groundbreaking feature that allows developers to build components that run on the server, enabling efficient data fetching and reducing client-side JavaScript. This approach enhances performance by sending minimal JavaScript to the client and improves the user experience by delivering faster load times. RSCs also simplify the development process by allowing direct access to server-side resources within components.

2. Latest MongoDB Updates

MongoDB has introduced several updates aimed at enhancing scalability, performance, and developer productivity. The introduction of time series collections optimizes the handling of time-based data, making it ideal for IoT and financial analytics applications. Additionally, MongoDB’s advancements in analytics capabilities allow for real-time processing of vast datasets, a feature particularly useful for AI-driven applications like recommendation engines and fraud detection.

3. Integrating GraphQL with the MERN Stack

GraphQL has gained popularity as a query language for APIs, offering a more efficient and flexible alternative to REST. Integrating GraphQL into the MERN stack allows developers to request specific data, reducing over-fetching and under-fetching issues. This integration enhances the efficiency of data retrieval and provides a more streamlined development experience.

4. Deployment Best Practices

Modern deployment practices have evolved to include containerization and orchestration tools:

  • Docker: Enables consistent environments across development and production by containerizing applications.
  • Kubernetes: Orchestrates containerized applications, managing scaling, deployment, and operations.
  • AWS: Offers a suite of services for deploying and scaling MERN applications, including Elastic Beanstalk and EC2.

Adopting these tools ensures scalable, resilient, and efficient deployment pipelines for MERN applications. Staying updated with these trends will empower developers to build robust, efficient, and modern applications using the MERN stack.

Common Mistakes to Avoid in MERN Stack Interviews

These are the common mistakes you must avoid during an interview –

  • Overlooking JavaScript Fundamentals
    • A strong understanding of JavaScript is the backbone of the MERN stack. Interviewers often test your knowledge of closures, async/await, the event loop, and ES6+ features. Don’t rush into advanced topics without mastering the basics.
  • Ignoring Performance Optimizations in Code Examples
    • Writing functional code is good, but optimized code is better. For example, in React, use React.memo, useMemo, and useCallback to avoid unnecessary re-renders. In MongoDB, demonstrate knowledge of indexing and efficient query design.
  • Failing to Test Applications Thoroughly
    • Be prepared to discuss testing strategies. Ignoring unit tests, integration tests, or even manual tests can give the impression that you don’t value software reliability. Use tools like Jest or Mocha for testing Node.js and React code.
  • Skipping Real-World Scenarios
    • Be ready to discuss and solve practical challenges, like handling errors in APIs, designing schemas, or scaling applications. Theory is essential, but practical application is what gets you the job.
  • Overcomplicating Answers
    • Keep your explanations clear and concise. Interviewers value simplicity and the ability to explain complex ideas in a way that’s easy to understand.

Conclusion

The MERN stack is one of the most in-demand technologies in 2025, offering exciting opportunities for developers. Interview preparation requires a solid understanding of JavaScript fundamentals, MERN components, and their integration. Mastering the basics, diving into advanced topics, and solving real-world challenges will set you apart.

This guide provides you with a comprehensive set of questions and insights to confidently tackle any MERN stack interview. Remember, practice is key—apply what you learn by building projects, experimenting with performance optimizations, and testing your skills with coding challenges.

Certified MERN Stack Developer
Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top 100 ReactJS Interview Questions 2025

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?