MERN Stack Interview Questions (2025)


The Ultimate Guide to MERN Stack Interview Questions

The MERN stack (MongoDB, Express.js, React.js, Node.js) is a powerful JavaScript-based framework for building full-stack web applications. This guide offers over 20 interview questions per component, with detailed answers to help you understand concepts thoroughly and excel in interviews. Let’s dive into each section!


MongoDB Questions

1. What is MongoDB, and how does it differ from traditional relational databases?

Answer: MongoDB is a NoSQL, document-oriented database designed to handle large volumes of unstructured or semi-structured data. It stores data in a flexible, JSON-like format called BSON (Binary JSON), which allows for dynamic schemas. Traditional relational databases (e.g., MySQL, PostgreSQL) use a structured schema with tables, rows, and columns, enforcing strict relationships via foreign keys.

  • Key Differences:
  • Schema Flexibility: MongoDB doesn’t require a predefined schema, making it ideal for evolving applications, whereas RDBMS requires a fixed schema.
  • Data Model: MongoDB uses documents within collections; RDBMS uses tables with rows and columns.
  • Scalability: MongoDB scales horizontally (via sharding), distributing data across servers, while RDBMS typically scales vertically (adding more power to a single server).
  • Joins: MongoDB avoids complex joins, embedding related data in documents, while RDBMS relies heavily on joins.
  • Use Case: MongoDB is suited for applications like content management systems or real-time analytics, while RDBMS excels in structured data scenarios like banking systems.

2. What are collections and documents in MongoDB?

Answer: In MongoDB, data is organized into collections and documents.

  • Collection: A collection is a group of MongoDB documents, analogous to a table in a relational database. It doesn’t enforce a schema, so documents within a collection can have different structures.
  • Document: A document is a single record within a collection, stored as a BSON object with key-value pairs. It’s akin to a row in a table but more flexible.

Example:

// Collection: "users"
{
  "_id": "12345",
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com"
}
  • Here, "users" is the collection, and the JSON object is a document. The _id field is a unique identifier automatically generated by MongoDB unless specified.

3. How do you perform CRUD operations in MongoDB?

Answer: CRUD stands for Create, Read, Update, and Delete—the fundamental operations for managing data. MongoDB provides a rich query language to perform these operations efficiently.

  • Create: Use insertOne() or insertMany() to add documents.
  • Read: Use find() for multiple documents or findOne() for a single document.
  • Update: Use updateOne() or updateMany() with operators like $set to modify data.
  • Delete: Use deleteOne() or deleteMany() to remove documents.

Code Example (Using MongoDB Node.js driver):

const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';

async function run() {
  const client = new MongoClient(url);
  try {
    await client.connect();
    const db = client.db('mydb');
    const collection = db.collection('users');

    // Create: Insert a single document
    await collection.insertOne({ name: 'Jane', age: 25, email: 'jane@example.com' });
    console.log('Document inserted');

    // Read: Find a document
    const user = await collection.findOne({ name: 'Jane' });
    console.log('Found user:', user);

    // Update: Modify the document
    await collection.updateOne({ name: 'Jane' }, { $set: { age: 26 } });
    console.log('Document updated');

    // Delete: Remove the document
    await collection.deleteOne({ name: 'Jane' });
    console.log('Document deleted');
  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}
run();
  • Explanation: This code connects to a local MongoDB instance, performs all CRUD operations on the users collection, and logs the results. Error handling ensures robustness.

4. What is an index in MongoDB, and why is it important?

Answer: An index in MongoDB is a data structure that improves query performance by allowing the database to locate documents efficiently without scanning the entire collection (a process called a collection scan). Indexes are created on specific fields and can be single-field, compound, or multi-key (for arrays).

  • Why Important: Without indexes, queries on large datasets become slow, especially for filtering or sorting. Indexes reduce time complexity from O(n) to O(log n) in many cases.
  • Trade-offs: Indexes consume additional storage and slightly slow down write operations (inserts, updates, deletes) due to index maintenance.

Example:

// Create an index on the "email" field
db.collection('users').createIndex({ email: 1 }); // 1 for ascending, -1 for descending
  • Explanation: This creates an ascending index on the email field, speeding up queries like find({ email: 'john@example.com' }).

5. What is aggregation in MongoDB?

Answer: Aggregation is a powerful feature in MongoDB for processing and transforming data through a pipeline of stages. Each stage performs an operation (e.g., filtering, grouping, sorting) and passes the result to the next stage. It’s similar to SQL’s GROUP BY but more flexible.

  • Common Stages:
  • $match: Filters documents.
  • $group: Groups documents and computes aggregates (e.g., sum, average).
  • $sort: Sorts the results.

Example:

db.collection('orders').aggregate([
  { $match: { status: 'completed' } }, // Filter completed orders
  { $group: { _id: '$customerId', total: { $sum: '$amount' } } }, // Sum amounts per customer
  { $sort: { total: -1 } } // Sort by total in descending order
]);
  • Explanation: This pipeline finds completed orders, groups them by customer, calculates the total amount spent, and sorts customers by their spending.

6. What is sharding in MongoDB?

Answer: Sharding is a method of horizontal scaling in MongoDB, where data is partitioned across multiple servers (shards). Each shard holds a subset of the data, improving performance and storage capacity for large datasets.

  • Components:
  • Shard: A server or replica set holding a data subset.
  • Mongos: A router that directs queries to the appropriate shard.
  • Config Servers: Store metadata about shard distribution.
  • Shard Key: A field used to split data (e.g., userId).
  • Use Case: Sharding is ideal for applications with massive datasets, like social media platforms.

7. What is replication in MongoDB?

Answer: Replication creates redundant copies of data across multiple servers (a replica set) to ensure high availability and fault tolerance. A replica set consists of a primary node (handles writes) and secondary nodes (replicate data for reads).

  • Benefits:
  • Failover: If the primary fails, a secondary is elected as the new primary.
  • Read Scaling: Secondary nodes can handle read requests.
  • Configuration: Uses an oplog (operation log) to synchronize changes.

8. How do you query nested documents in MongoDB?

Answer: MongoDB supports querying nested fields using dot notation, allowing access to embedded documents or arrays.

Example:

{
  "_id": "1",
  "name": "Alice",
  "address": { "city": "New York", "zip": "10001" }
}
db.collection('users').findOne({ "address.city": "New York" });
  • Explanation: The dot notation "address.city" targets the nested city field. This is useful for hierarchical data like user profiles.

9. What is the $lookup operator in aggregation?

Answer: The $lookup operator performs a left outer join between two collections, combining documents based on matching fields. It’s useful for retrieving related data without embedding it.

Example:

db.collection('orders').aggregate([
  {
    $lookup: {
      from: 'users',           // Target collection
      localField: 'userId',    // Field in "orders"
      foreignField: '_id',     // Field in "users"
      as: 'userDetails'        // Output array
    }
  }
]);
  • Explanation: This joins orders with users, adding user details to each order document.

10. What are capped collections?

Answer: Capped collections are fixed-size collections that automatically overwrite the oldest data when full, following a FIFO (First In, First Out) order. They’re useful for logs or caching.

Example:

db.createCollection('logs', { capped: true, size: 5242880 }); // 5MB cap

11. How do you handle transactions in MongoDB?

Answer: MongoDB supports multi-document ACID transactions since version 4.0, allowing atomic updates across multiple documents or collections.

Example:

const client = new MongoClient(url);
await client.connect();
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    const coll = client.db('mydb').collection('inventory');
    await coll.updateOne({ _id: 1 }, { $inc: { stock: -1 } });
    await coll.insertOne({ _id: 2, stock: 10 });
  });
} finally {
  await session.endSession();
  await client.close();
}
  • Explanation: This transaction decreases stock in one document and adds a new item atomically.

12. What is the difference between find() and findOne()?

Answer:

  • find(): Returns a cursor to multiple documents matching the query. You can iterate over it or convert it to an array.
  • findOne(): Returns the first document that matches the query or null if none exist.

Example:

// find()
const allUsers = await collection.find({ age: { $gt: 25 } }).toArray();
// findOne()
const user = await collection.findOne({ name: 'Jane' });

13. What is BSON, and why does MongoDB use it?

Answer: BSON (Binary JSON) is a binary-encoded serialization of JSON-like documents. MongoDB uses BSON for storage and transmission because it’s more efficient than plain JSON:

  • Supports additional data types (e.g., Date, Binary).
  • Faster parsing and smaller size due to binary format.

14. How do you sort data in MongoDB?

Answer: Use the sort() method with a field and direction (1 for ascending, -1 for descending).

Example:

db.collection('users').find().sort({ age: -1 }); // Sort by age descending

15. What are MongoDB operators?

Answer: Operators (e.g., $set, $inc, $push) are used in queries and updates to perform specific actions.

  • Example: $inc increments a field value.
db.collection('users').updateOne({ name: 'John' }, { $inc: { age: 1 } });

16. How do you limit and skip results in MongoDB?

Answer: Use limit() to restrict the number of documents and skip() to bypass a number of documents.

Example:

db.collection('users').find().skip(10).limit(5); // Page 3 with 5 items

17. What is the $unset operator?

Answer: $unset removes a field from a document.

Example:

db.collection('users').updateOne({ name: 'John' }, { $unset: { email: '' } });

18. How do you perform a text search in MongoDB?

Answer: Create a text index and use the $text operator.

Example:

db.collection('articles').createIndex({ content: 'text' });
db.collection('articles').find({ $text: { $search: 'MongoDB' } });

19. What is the difference between $push and $addToSet?

Answer:

  • $push: Adds an element to an array, allowing duplicates.
  • $addToSet: Adds an element only if it doesn’t already exist.

Example:

db.collection('users').updateOne({ name: 'John' }, { $push: { tags: 'dev' } });
db.collection('users').updateOne({ name: 'John' }, { $addToSet: { tags: 'dev' } });

20. What is the $project stage in aggregation?

Answer: $project reshapes documents by including, excluding, or renaming fields.

Example:

db.collection('users').aggregate([
  { $project: { name: 1, _id: 0 } } // Only include name
]);

21. How do you drop a collection in MongoDB?

Answer: Use drop() to delete a collection and its data.

Example:

db.collection('users').drop();

22. What is the $exists operator?

Answer: $exists checks if a field exists in a document.

Example:

db.collection('users').find({ email: { $exists: true } });

23. How do you backup and restore a MongoDB database?

Answer: Use mongodump to backup and mongorestore to restore.

  • Backup: mongodump --db mydb --out ./backup
  • Restore: mongorestore --db mydb ./backup/mydb

Express.js Questions

1. What is Express.js, and why is it used?

Answer: Express.js is a lightweight, unopinionated web framework for Node.js that simplifies building server-side applications and RESTful APIs. It provides a robust set of features like routing, middleware, and HTTP utilities.

  • Why Used:
  • Reduces boilerplate code for handling HTTP requests.
  • Supports middleware for tasks like logging, authentication, etc.
  • Integrates seamlessly with MongoDB and React in the MERN stack.
  • Use Case: Building APIs for a React front-end.

2. How do you create a basic Express server?

Answer: Setting up an Express server involves initializing the app, defining routes, and starting the server.

Example:

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Welcome to Express!');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
  • Explanation: This creates a server that responds with a message on the root route.

3. What is middleware in Express.js?

Answer: Middleware functions are executed in sequence between a request and response. They have access to req (request), res (response), and next (to pass control to the next middleware).

  • Types:
  • Application-level: app.use()
  • Route-level: router.use()
  • Error-handling: Four-parameter functions.

Example:

app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});
  • Explanation: This logs every request’s method and URL.

4. How do you handle errors in Express.js?

Answer: Error-handling middleware uses four parameters (err, req, res, next) and is defined after routes to catch errors.

Example:

app.get('/error', (req, res) => {
  throw new Error('Test error');
});

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});
  • Explanation: This catches errors and sends a JSON response.

5. What are RESTful routes, and how do you implement them?

Answer: RESTful routes follow REST architecture, mapping HTTP methods to CRUD operations.

Example:

app.get('/users', (req, res) => res.send('List users')); // Read all
app.get('/users/:id', (req, res) => res.send(`User ${req.params.id}`)); // Read one
app.post('/users', (req, res) => res.send('Create user')); // Create
app.put('/users/:id', (req, res) => res.send('Update user')); // Update
app.delete('/users/:id', (req, res) => res.send('Delete user')); // Delete

6. How do you parse request bodies in Express?

Answer: Use built-in middleware like express.json() or express.urlencoded().

Example:

app.use(express.json());
app.post('/data', (req, res) => {
  console.log(req.body); // Parsed JSON
  res.send('Data received');
});

7. What is routing in Express.js?

Answer: Routing defines how an application responds to client requests based on URL paths and HTTP methods.

Example:

const router = express.Router();
router.get('/about', (req, res) => res.send('About page'));
app.use('/api', router);

8. How do you serve static files in Express?

Answer: Use express.static() to serve files like HTML, CSS, or images.

Example:

app.use(express.static('public')); // Serve files from "public" folder

9. What is the purpose of next() in Express?

Answer: next() passes control to the next middleware or route handler in the stack. Without it, the request hangs.

Example:

app.use((req, res, next) => {
  req.customData = 'Hello';
  next();
});
app.get('/', (req, res) => res.send(req.customData));

10. How do you handle query parameters in Express?

Answer: Access query parameters via req.query.

Example:

app.get('/search', (req, res) => {
  const { q } = req.query; // e.g., /search?q=nodejs
  res.send(`Search term: ${q}`);
});

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

Answer: CORS (Cross-Origin Resource Sharing) allows restricted resources to be requested from another domain. Use the cors package.

Example:

const cors = require('cors');
app.use(cors({ origin: 'http://localhost:3000' }));

12. How do you implement authentication in Express?

Answer: Use middleware like jsonwebtoken for token-based authentication.

Example:

const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
  const token = jwt.sign({ id: 1 }, 'secret');
  res.json({ token });
});

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

Answer:

  • app.use(): Applies middleware to all requests or a specific path.
  • app.get(): Handles GET requests for a specific route.

14. How do you validate request data in Express?

Answer: Use libraries like express-validator.

Example:

const { body, validationResult } = require('express-validator');
app.post('/user', [body('email').isEmail()], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) return res.status(400).json(errors.array());
  res.send('Valid');
});

15. How do you handle file uploads in Express?

Answer: Use multer middleware.

Example:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded');
});

16. What is the Router class in Express?

Answer: Router modularizes route handling.

Example:

const router = express.Router();
router.get('/users', (req, res) => res.send('Users'));
app.use('/api', router);

17. How do you set HTTP headers in Express?

Answer: Use res.set() or res.header().

Example:

app.get('/data', (req, res) => {
  res.set('Content-Type', 'application/json');
  res.send({ message: 'Hello' });
});

18. How do you redirect in Express?

Answer: Use res.redirect().

Example:

app.get('/old', (req, res) => {
  res.redirect('/new');
});

19. What is express-session?

Answer: A middleware for managing user sessions.

Example:

const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized: false }));

20. How do you rate-limit requests in Express?

Answer: Use express-rate-limit.

Example:

const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); // 100 requests per 15 min

21. How do you compress responses in Express?

Answer: Use compression middleware.

Example:

const compression = require('compression');
app.use(compression());

22. What is the purpose of helmet in Express?

Answer: helmet secures Express apps by setting HTTP headers.

Example:

const helmet = require('helmet');
app.use(helmet());

23. How do you handle 404 errors in Express?

Answer: Define a catch-all middleware.

Example:

app.use((req, res) => {
  res.status(404).send('Page not found');
});

React.js Questions

1. What is React.js, and what are its key features?

Answer: React.js is a JavaScript library for building user interfaces, particularly SPAs. It uses a component-based architecture and a virtual DOM.

  • Key Features:
  • Components: Reusable UI building blocks.
  • Virtual DOM: Optimizes rendering.
  • JSX: HTML-like syntax in JavaScript.
  • Hooks: State and lifecycle in functional components.

2. What is JSX, and how does it work?

Answer: JSX is a syntax extension that combines HTML and JavaScript. It’s transpiled by Babel into React.createElement() calls.

Example:

const element = <h1>Hello</h1>;
// Becomes:
React.createElement('h1', null, 'Hello');

3. What are React Hooks?

Answer: Hooks (introduced in 16.8) allow state and lifecycle management in functional components.

Example:

import React, { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

4. What is the difference between props and state?

Answer:

  • Props: Immutable, passed from parent to child.
  • State: Mutable, managed within a component.

Example:

function Child({ message }) {
  return <p>{message}</p>;
}
function Parent() {
  const [count, setCount] = useState(0);
  return <Child message={`Count: ${count}`} />;
}

5. What is the Virtual DOM?

Answer: A lightweight copy of the real DOM. React uses it to compute changes (diffing) and update the real DOM efficiently (reconciliation).

6. What is a functional component?

Answer: A JavaScript function that returns JSX.

Example:

function Welcome() {
  return <h1>Hello</h1>;
}

7. What is a class component?

Answer: A component defined as an ES6 class with a render() method.

Example:

class Welcome extends React.Component {
  render() {
    return <h1>Hello</h1>;
  }
}

8. What is useEffect Hook?

Answer: Handles side effects (e.g., data fetching) in functional components.

Example:

useEffect(() => {
  document.title = 'React App';
}, []);

9. What is the purpose of keys in React?

Answer: Keys help React identify which items in a list have changed, added, or removed.

Example:

const items = ['A', 'B'].map((item, index) => <li key={index}>{item}</li>);

10. What is React Router?

Answer: A library for routing in React applications.

Example:

import { BrowserRouter, Route } from 'react-router-dom';
function App() {
  return (
    <BrowserRouter>
      <Route path="/" exact component={Home} />
    </BrowserRouter>
  );
}

11. What is Redux?

Answer: A state management library for predictable state updates.

12. What is the useContext Hook?

Answer: Accesses context values without prop drilling.

Example:

const ThemeContext = React.createContext('light');
function App() {
  const theme = useContext(ThemeContext);
  return <div>{theme}</div>;
}

13. What is useReducer Hook?

Answer: Manages complex state logic, similar to Redux.

Example:

const [state, dispatch] = useReducer((state, action) => {
  switch (action.type) {
    case 'increment': return state + 1;
    default: return state;
  }
}, 0);

14. How do you handle forms in React?

Answer: Use controlled components with state.

Example:

function Form() {
  const [value, setValue] = useState('');
  return <input value={value} onChange={e => setValue(e.target.value)} />;
}

15. What is PropTypes?

Answer: Validates prop types for components.

Example:

import PropTypes from 'prop-types';
function User({ name }) {
  return <p>{name}</p>;
}
User.propTypes = { name: PropTypes.string.isRequired };

16. What is the difference between controlled and uncontrolled components?

Answer:

  • Controlled: Value managed by React state.
  • Uncontrolled: Value managed by DOM (e.g., via refs).

17. What is React Fragments?

Answer: Allows grouping children without adding extra DOM nodes.

Example:

return <><h1>Title</h1><p>Text</p></>;

18. What is the useMemo Hook?

Answer: Memoizes expensive computations.

Example:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

19. What is the useCallback Hook?

Answer: Memoizes callback functions.

Example:

const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);

20. How do you optimize performance in React?

Answer: Use memoization (React.memo, useMemo), lazy loading, and avoid unnecessary renders.

21. What is lazy loading in React?

Answer: Loads components only when needed.

Example:

const LazyComponent = React.lazy(() => import('./Component'));

22. What is the difference between useState and useReducer?

Answer: useState is for simple state; useReducer is for complex state logic.

23. How do you fetch data in React?

Answer: Use useEffect with fetch or libraries like Axios.

Example:

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => setData(data));
}, []);

Node.js Questions

1. What is Node.js?

Answer: Node.js is a runtime environment that executes JavaScript on the server side using the V8 engine. It’s single-threaded but non-blocking due to its event-driven architecture.

2. What is the event loop?

Answer: The event loop manages asynchronous operations in Node.js, ensuring non-blocking I/O.

3. How do you handle asynchronous operations?

Answer: Use callbacks, Promises, or async/await.

Example:

async function fetchData() {
  const data = await fetch('https://api.example.com');
  return data.json();
}

4. What is npm?

Answer: Node Package Manager for installing and managing dependencies.

5. What is the difference between process.nextTick() and setImmediate()?

Answer: nextTick runs before the next event loop phase; setImmediate runs in the next iteration.

6. What is the fs module?

Answer: Handles file system operations.

Example:

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => console.log(data));

7. What is require in Node.js?

Answer: Imports modules.

Example:

const express = require('express');

8. What is the http module?

Answer: Creates HTTP servers.

Example:

const http = require('http');
http.createServer((req, res) => res.end('Hello')).listen(3000);

9. What is a Promise?

Answer: An object representing the eventual completion or failure of an async operation.

10. What is async/await?

Answer: Syntactic sugar over Promises.

Example:

async function run() {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('Done');
}

11. What is the path module?

Answer: Handles file paths.

Example:

const path = require('path');
console.log(path.join(__dirname, 'file.txt'));

12. What is cluster in Node.js?

Answer: Enables multi-core usage.

Example:

const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
} else {
  console.log('Worker');
}

13. What is buffer in Node.js?

Answer: Handles binary data.

Example:

const buf = Buffer.from('Hello');
console.log(buf.toString());

14. How do you handle errors in Node.js?

Answer: Use try-catch or event emitters.

Example:

try {
  throw new Error('Test');
} catch (e) {
  console.error(e);
}

15. What is the os module?

Answer: Provides OS-related utilities.

Example:

const os = require('os');
console.log(os.cpus());

16. What is EventEmitter?

Answer: A class for handling custom events.

Example:

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('event', () => console.log('Fired'));
emitter.emit('event');

17. What is the difference between fork() and spawn()?

Answer: fork() is for Node.js processes; spawn() is for any command.

18. How do you debug Node.js applications?

Answer: Use console.log, --inspect, or tools like VS Code debugger.

19. What is package.json?

Answer: Defines project metadata and dependencies.

20. What is the crypto module?

Answer: Provides cryptographic functionality.

Example:

const crypto = require('crypto');
console.log(crypto.createHash('sha256').update('data').digest('hex'));

21. How do you stream data in Node.js?

Answer: Use streams for large data.

Example:

const fs = require('fs');
fs.createReadStream('file.txt').pipe(process.stdout);

22. What is process in Node.js?

Answer: A global object providing info about the current process.

Example:

console.log(process.env.NODE_ENV);

23. How do you secure a Node.js app?

Answer: Use HTTPS, sanitize inputs, and manage secrets.


General MERN Stack Questions

1. What is the MERN stack?

Answer: A full-stack framework using MongoDB, Express.js, React.js, and Node.js.

2. How do components interact in MERN?

Answer: React sends HTTP requests to Express/Node, which queries MongoDB.

3. How do you connect React to Express?

Answer: Use fetch or Axios.

Example:

fetch('/api/data').then(res => res.json()).then(data => console.log(data));

4. What is JWT, and how is it used in MERN?

Answer: JSON Web Tokens for authentication.

5. How do you deploy a MERN app?

Answer: Build React, serve via Express, deploy to Heroku/AWS.

6. What is CORS in MERN?

Answer: Manages cross-origin requests.

7. How do you secure a MERN app?

Answer: Use JWT, Helmet, HTTPS, etc.

8. What is the role of environment variables?

Answer: Store sensitive data.

Example:

require('dotenv').config();
console.log(process.env.DB_URL);

9. How do you handle file uploads in MERN?

Answer: Use multer in Express, send via FormData in React.

10. What is SSR in MERN?

Answer: Server-side rendering with React.

11. How do you optimize a MERN app?

Answer: Use lazy loading, caching, and efficient queries.

12. What is the difference between SPA and MPA in MERN?

Answer: SPA (React) vs. traditional multi-page apps.

13. How do you test a MERN app?

Answer: Use Jest for React, Mocha for Node.js.

14. What is middleware’s role in MERN?

Answer: Handles authentication, logging, etc.

15. How do you manage state in MERN?

Answer: Use React state, Context, or Redux.

16. What is GraphQL, and can it replace REST in MERN?

Answer: A query language for APIs, offering flexibility.

17. How do you handle real-time data in MERN?

Answer: Use WebSockets or libraries like Socket.IO.

18. What is the role of nodemon in MERN?

Answer: Restarts the server on code changes.

19. How do you structure a MERN project?

Answer: Separate client (React) and server (Express/Node).

20. What is the benefit of using MERN?

Answer: Unified JavaScript, full-stack consistency.

21. How do you handle versioning in MERN APIs?

Answer: Use URL prefixes (e.g., /v1/users).

22. What is the role of axios in MERN?

Answer: Simplifies HTTP requests from React.

23. How do you scale a MERN app?

Answer: Use load balancers, sharding, and caching.


Apply now and take your first step towards a successful career in Web Development! Placement Guarantee Program