Our Process

Get Paper Done In 3 Simple Steps

Place an order

Visit the URL and place your order with us. Fill basic details of your research paper, set the deadlines and submit the form.

Make payments

Chat with our experts to get the best quote. Make the payment via online banking, debit/credit cards or through paypal. Recieve an order confirmation number.

Receive your paper

Sit back and relax. Your well written, properly referenced research paper will be mailed to your inbox, before deadline. Download the paper. Revise and Submit.

Shape Thumb
Shape Thumb
Shape Thumb
  • Evan John Evan John
  • 22 min read

Mern Stack Technical Interview Questions

Looking for MERN Stack Interview Questions? Mastering MongoDB, Express.js, React, and Node.js is essential for any developer diving into modern web development. Whether you’re just starting out or already have experience, showcasing your skills with the MERN stack can set you apart from the competition.

Below is a curated list of technical interview questions designed specifically for the MERN stack. These questions will help you strengthen your understanding and confidently tackle even the most challenging interview scenarios.

MERN Stack Interview Questions

20 Most Popular MERN Stack Interview Questions

1. What is the MERN stack? Why is it popular?

Answer:
MERN stands for MongoDB, Express.js, React.js, and Node.js — a full-stack JavaScript-based technology stack used to build scalable, modern web apps. It’s popular due to:

  • End-to-end JavaScript

  • Scalability

  • Large community support

  • Flexible data models with MongoDB

2. Explain the role of each component in MERN.

  • MongoDB: NoSQL database

  • Express.js: Node.js web framework

  • React: Frontend library for UI

  • Node.js: Server-side runtime

3. How does the data flow in a MERN stack application?

Answer:

  1. React (client) sends a request via HTTP.

  2. Express (server) receives it and processes logic.

  3. Node.js handles the backend and interacts with MongoDB.

  4. MongoDB returns data → Express → React.

 

4. What is JSX in React?

Answer: JSX is a syntax extension for JavaScript that lets you write HTML-like code in React. Example:

const element = <h1>Hello World</h1>;

5. How do you manage state in a React app?

Answer:

  • Local state: useState

  • Global state: Context API, Redux, Zustand, Recoil

  • Server state: React Query / SWR

6. Difference between Functional and Class Components in React?

  • Functional: Uses hooks (useState, useEffect)

  • Class: Uses lifecycle methods (componentDidMount, etc.)

7. How do you create a RESTful API using Express.js?

Answer:

const express = require('express');
const app = express();
app.get(‘/api/users’, (req, res) => {
res.json({ name: ‘John Doe’ });
});

8. How do you handle forms in React?

Answer:

const [form, setForm] = useState({ name: "" });
<input value={form.name} onChange={(e) => setForm({ name: e.target.value })} /> 

9. What is useEffect in React?

Answer:
useEffect is a hook to run side effects like API calls or event listeners.

10. What are MongoDB documents and collections?

Answer:

  • Documents: JSON-like data records (similar to rows)

  • Collections: Group of documents (similar to tables)

11. How do you connect MongoDB to Node.js using Mongoose?

Answer:

mongoose.connect('mongodb://localhost:27017/myapp');

12. Explain middleware in Express.js.

Answer: Middleware functions run before route handlers. They can modify requests, responses, or end cycles.

13. What is the Virtual DOM in React?

Answer:
A lightweight in-memory representation of the real DOM. React updates it first and then efficiently updates the real DOM.

14. What is the use of useState in React?

Answer: To hold and manage local state in functional components.

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

15. What are controlled components in React?

Answer:
Components whose form inputs are controlled via React state.

16. What is the difference between MongoDB and SQL databases?

  • MongoDB: NoSQL, JSON-like documents, schema-less

  • SQL: Relational, structured schema, uses tables

17. How do you create a schema and model in Mongoose?

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String });
module.exports = mongoose.model('User', userSchema);

18. How do you implement routing in React?

Answer:

import { BrowserRouter, Route, Routes } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>

19. How do you secure APIs using JWT in MERN stack?

  • Generate JWT on login

  • Store in client (localStorage/cookies)

  • Send in Authorization header

  • Validate on protected routes

20. How would you deploy a MERN app?

Answer:

  • Frontend (React): Deployed on Netlify, Vercel, or S3

  • Backend (Node/Express): Deployed on Heroku, Railway, or Render

  • Database (MongoDB): MongoDB Atlas

  • Env Setup: .env files and secure keys

Beginner Level 

       1. What is the MERN Stack, and why is it popular?

Answer: The MERN stack comprises four technologies:

  • MongoDB: A NoSQL database for storing data in flexible, JSON-like documents.

  • Express.js: A web application framework for Node.js that simplifies server-side coding.

  • React.js: A JavaScript library for building user interfaces, particularly single-page applications.

  • Node.js: A JavaScript runtime that allows server-side execution of JavaScript code.

Its popularity stems from its use of JavaScript on both the client and server sides, facilitating seamless development and efficient data flow between components.

    • The MERN stack is a JavaScript-based full-stack development framework comprising MongoDB (NoSQL database), Express.js (web application framework), React (frontend library), and Node.js (JavaScript runtime).

  1. Explain the role of each component in the MERN stack.

    • MongoDB: Stores data in a flexible, JSON-like format.

    • Express.js: Handles server-side logic and routing.

    • React: Builds dynamic user interfaces

    • Node.js: Executes JavaScript code on the server side.

  2. Why choose the MERN stack for web development?

    • It allows for end-to-end JavaScript development, facilitating seamless integration between frontend and backend, and benefits from a large community and extensive libraries.

  3. What are the advantages of using MongoDB in the MERN stack?

    • MongoDB offers a flexible schema design, horizontal scalability, and stores data in a JSON-like format, which aligns well with JavaScript-based applications.

  4. How does Node.js handle asynchronous operations?

    • Node.js uses an event-driven, non-blocking I/O model, allowing it to handle multiple operations concurrently without waiting for previous tasks to complete.

  5. What is Express.js, and how does it simplify server-side development?

    • Express.js is a minimal and flexible Node.js web application framework that provides robust features for building web and mobile applications, simplifying tasks like routing, middleware integration, and request handling.

  6. Describe the virtual DOM in React.

    • The virtual DOM is a lightweight JavaScript representation of the real DOM. React uses it to optimize rendering by updating only the changed parts of the DOM, enhancing performance.

  7. How do you create a basic route in Express.js?

    const express = require('express');
    const app = express();
    app.get('/', (req, res) => {
    res.send('Hello World');
    });
    app.listen(3000, () => {
    console.log('Server is running on port 3000');
    });
  8. What is JSX in React?

    • JSX stands for JavaScript XML. It allows developers to write HTML elements and components in JavaScript, which React transforms into standard JavaScript objects.

  9. How do you pass data between React components?

    • Data can be passed from parent-to-child components using props and from child to parent using callback functions. Tools like Redux or Context API can be used for complex state management.

  10. How would you architect a scalable MERN stack application with role-based access and real-time updates?

    What this tests:

    • System design capabilities

    • Authentication/authorization knowledge (JWT, OAuth, RBAC)

    • Real-time communication using WebSockets (e.g., Socket.IO)

    • Code organization and scalability planning

    What to cover in your answer:

    • Backend:

      • Use Express.js + Node.js

      • Structure controllers, routes, services for modularity

      • Use JWT for auth, middleware for RBAC

      • Use Redis (optional) for session or pub/sub caching

    • Frontend:

      • Use React with React Router for SPA routing

      • Role-aware route protection (HOC or custom hooks)

      • Real-time updates via Socket.IO client

    • Database:

      • MongoDB schema design

      • Use Mongoose for schema-based modeling

    • DevOps:

      • Dockerize the app

      • Use environment-based configs (dotenv)

      • Deploy on platforms like Vercel (frontend) and AWS/GCP (backend)

    12. Explain how to implement secure user authentication and session management in a MERN stack app.

    What this tests:

    • Security understanding

    • Auth/session lifecycle

    • Cookie vs. token-based auth tradeoffs

    What to cover in your answer:

    • Use bcrypt to hash passwords

    • Use JWT stored in HttpOnly cookies for better XSS protection

    • Implement refresh tokens and access token lifecycle (short-lived tokens)

    • Use CSRF protection (especially with cookies)

    • Validate input using libraries like Joi or Zod

    • Monitor for brute force login attempts (rate limiting, captcha)

    • Bonus: Mention OAuth 2.0 (e.g., Google login) and 2FA (TOTP or SMS)

     13. How do you optimize performance in large-scale React applications?

    What this tests:

    • Frontend optimization strategy

    • Real-world performance considerations

    What to cover in your answer:

    • Use React.memo, useMemo, useCallback to avoid unnecessary renders

    • Use dynamic import() and React.lazy/Suspense for code splitting

    • Debounce user input (e.g., search bars)

    • Use virtualization (e.g., react-window or react-virtualized) for rendering large lists

    • Keep component trees shallow — break into atomic design

    • Analyze bundle size with Webpack Bundle Analyzer

    • Pre-fetch data and cache using React Query or SWR

    • Minimize re-renders by flattening prop structures or memoizing context values

    14. How would you implement a microservices approach in a MERN-based architecture?

    What this tests:

    • Architectural thinking

    • Understanding of services, APIs, and communication protocols

    What to cover in your answer:

    • Break features into independent services:

      • Auth service

      • User service

      • Product/order service, etc.

    • Use REST APIs or GraphQL as communication layers

    • Use message brokers (e.g., RabbitMQ, Kafka) for decoupled communication

    • Each service has its own database (polyglot persistence) — e.g., MongoDB, Redis

    • Centralized logging and monitoring (e.g., ELK stack or Prometheus + Grafana)

    • Deploy using Docker and orchestrate with Kubernetes (or simpler tools like Docker Compose for small setups)

    • Ensure backward compatibility in APIs and use API gateways (like Kong or NGINX)

Express.js

  1. What role does Express.js play in a MERN stack?
    • Discuss Express.js as a minimalist web application framework for Node.js, enabling the development of robust and scalable server-side applications.
  2. Explain the core features of Express.js.
    • Express.js provides detailed features like routing, middleware support, template engines, and HTTP utility methods for building web applications.
  3. How does Express handle routing, and why is it important?
    • Explain Express’s routing mechanism for mapping HTTP requests to specific endpoints, emphasizing its role in organizing application logic and handling different request types.
  4. Describe the use of middleware in an Express.js application.
    • Elaborate on middleware functions and their role in intercepting and modifying incoming requests or responses, enabling tasks like authentication, logging, or error handling.
  5. How can you handle file uploads in Express.js?
    • Explain how to use middleware like ‘multer’ in Express.js for handling file uploads, specifying file size limits, handling different file types, and storing uploaded files.
  6. Discuss the differences between app.use() and app.get() in Express.js.
    • Contrast app.use() as a middleware registration method and app.get() as a method for handling GET requests, explaining their respective uses and syntax.
  7. Explain error handling mechanisms in Express.js middleware.
    • Describe approaches for error handling, such as using synchronous and asynchronous middleware functions, the ‘next’ function, and the ‘error’ object.
  8. How does Express.js handle sessions and cookies?
    • Discuss session management and cookies in Express.js, covering middleware like ‘express-session’ for handling sessions and ‘cookie-parser’ for parsing cookies.
  9. Discuss the concept of template engines in Express.js.
    • Explain the purpose of template engines like EJS or Handlebars in Express.js for server-side rendering of dynamic content.
  10. What is the purpose of route parameters in Express.js?
    • Explain how route parameters are used to capture values from URL segments in Express.js and how they facilitate dynamic routing and handling of user input.
  11. Explain the concept of static files in Express.js and how to serve them.
    • Detail the use of Express.js to serve static files such as images, CSS, and client-side JavaScript, explaining the ‘express.static()’ middleware.
  12. How can you implement authentication using Passport.js with Express?
    • Discuss the integration of Passport.js, covering authentication strategies like local, OAuth, or JWT, and how they’re implemented with Express.js middleware.
  13. Discuss Express.js support for WebSockets.
    • Explain how libraries like ‘socket.io’ can be integrated into Express.js for real-time bidirectional communication between the client and server.
  14. Explain how to perform unit testing in an Express.js application.
    • Discuss testing tools like Mocha, Chai, or Jest for writing and executing unit tests in Express.js applications, covering mocking, stubbing, and assertions.
  15. How can you optimize Express.js applications for performance?
    • Discuss performance optimization techniques such as caching, gzip compression, load balancing, and minimizing blocking code for enhanced application performance.

Check on Comparison of MERN Tech Stack with Tech Stack

Advanced-Level Questions

  •  How does MongoDB differ from SQL databases?

Answer: MongoDB is a NoSQL database that stores data in flexible, JSON-like documents, allowing for dynamic schemas. In contrast, SQL databases use structured tables with predefined schemas, making them less adaptable to changes. MongoDB’s design suits applications requiring scalability and handling unstructured data.

  • What is the role of Express.js in the MERN stack?

Answer: Express.js is a lightweight web framework for Node.js that simplifies the development of server-side applications. It provides robust routing mechanisms, middleware integration, and tools for building APIs, facilitating communication between a MERN application’s front and back end.

  •  How does React.js differ from traditional JavaScript?

Answer: React.js allows developers to build user interfaces using a component-based architecture, promoting reusability and modularity. Unlike traditional JavaScript, which manipulates the DOM directly, React utilizes a virtual DOM to optimize rendering and improve performance.

  • What is Node.js, and why is it used in the MERN stack?

Answer: Node.js is a JavaScript runtime that enables the execution of JavaScript code on the server side. It uses an event-driven, non-blocking I/O model, making it efficient and suitable for scalable applications. In the MERN stack, Node.js allows developers to use JavaScript for both client-side and server-side programming, streamlining development processes.

  • How do you perform CRUD operations in MongoDB using Mongoose?

Answer: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model application data. CRUD operations can be performed as follows:

Create: Model.create(doc, callback)

Read: Model.find(query, callback)

Update: Model.findByIdAndUpdate(id, update, callback)

Delete: Model.findByIdAndDelete(id, callback)

These methods allow for efficient data manipulation within a MongoDB database.GUVI

  • What are React Hooks, and how do they improve state management?

Answer: React Hooks are functions that let developers use state, and other React features in functional components. Introduced in React 16.8, hooks like useState and useEffect allow for managing state and side effects without needing class components, leading to cleaner and more concise code.

  • Explain the event-driven architecture of Node.js.

Answer: Node.js operates on an event-driven architecture, utilizing an event loop to handle asynchronous operations. When an event occurs, such as a user request, Node.js places it in an event queue and processes it using callback functions, allowing for non-blocking I/O operations and efficient handling of concurrent connections.

  • What is middleware in Express.js?

Answer: Middleware in Express.js refers to functions with access to the request and response objects and can modify them or end the request-response cycle. Middleware functions are used for tasks such as authentication, logging, and error handling, and they can be stacked to handle complex operations.

  • How does the virtual DOM work in React?

Answer: The virtual DOM is a lightweight copy of the actual DOM maintained by React. When a component’s state changes, React updates the virtual DOM and compares it with the previous version using a process called “diffing.” It then updates only the parts of the actual DOM that have changed, resulting in efficient rendering and improved performance.

What is the purpose of keys in React lists?

Answer: Keys in React uniquely identify which items have changed, added, or removed in a list. They help React optimize rendering by reusing existing components rather than re-rendering the entire list, thus improving performance.

How do you handle forms in React?

Answer: In React, forms can be handled using controlled components, where form inputs are tied to the component’s state. The useState hook is commonly used to manage the state of form inputs, and event handlers  onChange update the state as the user types. This approach ensures that the React state is the single source of truth.

1. What is the MERN Stack, and why is it popular?
Answer: MERN stands for MongoDB, Express.js, React.js, and Node.js. It’s popular because it allows full-stack development using JavaScript across both client and server sides, streamlining development and improving consistency across the stack.

2. Explain the role of each component in the MERN stack.
Answer:

  • MongoDB: NoSQL database that stores data in a flexible, JSON-like format.

  • Express.js: Framework for building APIs and handling routing on the backend.

  • React.js: Frontend library for building user interfaces, especially SPAs.

  • Node.js: Runtime that enables executing JavaScript on the server side.

3. Why choose the MERN stack for web development?
Answer: It allows end-to-end JavaScript development, fast prototyping, reusability, and benefits from a large ecosystem of libraries and a strong community.

4. What are the advantages of using MongoDB in the MERN stack?
Answer: Schema flexibility, scalability, JSON-like document structure, and easy integration with Node.js.

5. How does Node.js handle asynchronous operations?
Answer: Using an event-driven, non-blocking I/O model with an event loop, allowing concurrent handling of multiple operations.

6. What is Express.js, and how does it simplify server-side development?
Answer: It’s a minimal web framework for Node.js that simplifies routing, middleware integration, and handling HTTP requests.

7. Describe the virtual DOM in React.
Answer: A virtual representation of the real DOM. React updates only changed elements in the real DOM, improving performance.

8. How do you create a basic route in Express.js?
Answer:

const express = require('express');
const app = express();
app.get(‘/’, (req, res) => {
res.send(‘Hello World’);
});app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});

9. What is JSX in React?
Answer: JavaScript XML – a syntax extension that allows writing HTML-like code in JavaScript. It’s transpiled to standard JavaScript by Babel.

10. How do you pass data between React components?
Answer:

  • Parent to Child: Using props

  • Child to Parent: Using callback functions

  • Global state: Using Context API or Redux

 Intermediate Level

11. How would you architect a scalable MERN stack application with role-based access and real-time updates?
Answer:

  • Backend: Modular Express architecture, JWT auth, RBAC middleware, Redis for caching.

  • Frontend: Role-aware routing with custom hooks, React Router, Socket.IO for real-time features.

  • Database: MongoDB with Mongoose schema.

  • DevOps: Dockerize the app, use environment configs, and deploy with Vercel (frontend) and AWS/GCP (backend).

12. How to implement secure authentication and session management?
Answer:

  • Use bcrypt for password hashing.

  • Use JWT in HttpOnly cookies.

  • Implement refresh tokens.

  • CSRF protection.

  • Input validation (e.g., Joi, Zod).

  • Rate limiting and optional OAuth or 2FA.

13. How do you optimize performance in React applications?
Answer:

  • Use React.memo, useMemo, useCallback.

  • Code splitting with React.lazy.

  • Debounce inputs.

  • Virtualize long lists.

  • Minimize re-renders and use flat props.

14. How to implement microservices in a MERN-based system?
Answer:

  • Split services (auth, users, products).

  • Use REST or GraphQL.

  • Communicate via message brokers (e.g., Kafka).

  • Each service has its own database.

  • Deploy with Docker/Kubernetes.

  • API gateways for routing.

15. What is middleware in Express.js?
Answer: Middleware functions intercept and modify requests/responses. Used for logging, authentication, error handling.

16. How does React manage state in functional components?
Answer: With the useState hook.

17. What is the useEffect hook in React?
Answer: It handles side effects like API calls or event listeners, triggered after render.

18. How do you handle forms in React?
Answer: Using controlled components tied to state via useState, or uncontrolled components using ref.

19. What is CORS, and how is it handled in MERN?
Answer: CORS restricts cross-origin requests. Handled using the cors middleware in Express.js.

20. How do you connect React frontend with Node.js backend?
Answer: By making HTTP requests using fetch or Axios from React to API endpoints defined in Express.

21. What are React Fragments?
Answer: A way to group multiple elements without adding extra DOM nodes (<></>).

22. What is lifting state in React?
Answer: Moving shared state to a common parent component.

23. How do you implement authentication in MERN?
Answer: Using JWTs issued on login and verified on protected routes.

24. What is the purpose of keys in React lists?
Answer: To uniquely identify list items for efficient DOM updates.

Advanced Level

25. How does MongoDB differ from SQL databases?
Answer: MongoDB uses flexible document schemas and stores data in JSON-like formats, whereas SQL uses rigid table schemas.

26. How do you perform CRUD operations with Mongoose?
Answer:

  • Create: Model.create()

  • Read: Model.find()

  • Update: Model.findByIdAndUpdate()

  • Delete: Model.findByIdAndDelete()

27. What are React Hooks, and how do they improve functional components?
Answer: Hooks like useState, useEffect let you manage state and side effects in functional components, avoiding class components.

28. What is Node.js’s event-driven architecture?
Answer: Node.js uses an event loop to handle async operations, enabling non-blocking I/O and concurrent request handling.

29. How does the virtual DOM improve performance?
Answer: It minimizes direct DOM manipulations by diffing a virtual copy and applying only the necessary changes.

30. How are forms handled in React using controlled components?
Answer: Input values are stored in the component’s state using useState, and changes are handled with onChange event handlers.

Advanced MERN Stack Interview Questions (with Programs)

31. How do you connect MongoDB with a Node.js application using Mongoose?

Answer:

const mongoose = require('mongoose');

mongoose.connect(‘mongodb://localhost:27017/mydb’, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log(‘MongoDB connected!’);
}).catch(err => {
console.error(‘Connection error:’, err);
});

 

32. Create a simple Express.js API with CRUD operations for a “Product” resource.

Answer:

const express = require('express');
const router = express.Router();
const Product = require('./models/Product');
// Create
router.post(‘/products’, async (req, res) => {
const product = new Product(req.body);
await product.save();
res.send(product);
});

// Read
router.get(‘/products’, async (req, res) => {
const products = await Product.find();
res.send(products);
});

// Update
router.put(‘/products/:id’, async (req, res) => {
const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(product);
});

// Delete
router.delete(‘/products/:id’, async (req, res) => {
await Product.findByIdAndDelete(req.params.id);
res.send({ message: ‘Deleted’ });
});


33. How do you manage global state in a React app using Context API?

Answer:

// Context.js
import { createContext, useContext, useState } from 'react';
export const AppContext = createContext();
export const AppProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<AppContext.Provider value={{ user, setUser }}>
{children}
</AppContext.Provider>
);
};export const useAppContext = () => useContext(AppContext); 

34. Write a simple login system using JWT in Express.js.

Answer:

const jwt = require('jsonwebtoken');

app.post(‘/login’, (req, res) => {
const user = { id: 1, name: “admin” }; // Sample
const token = jwt.sign(user, ‘secretkey’, { expiresIn: ‘1h’ });
res.json({ token });
});

const verifyToken = (req, res, next) => {
const bearer = req.headers[‘authorization’];
if (!bearer) return res.sendStatus(403);
jwt.verify(bearer.split(‘ ‘)[1], ‘secretkey’, (err, decoded) => {
if (err) return res.sendStatus(403);
req.user = decoded;
next();
});
};

35. Demonstrate lazy loading a component in React.

Answer:

import React, { Suspense, lazy } from 'react';

const LazyComponent = lazy(() => import(‘./LazyComponent’));

function App() {
return (
<Suspense fallback={<div>Loading…</div>}>
<LazyComponent />
</Suspense>
);
}

36. How do you deploy a MERN app using Docker?

Answer (Dockerfile for backend):

FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD ["node", "server.js"]

Answer 

version: '3'
services:
mongo:
image: mongo
ports:
- '27017:27017'
backend:
build: .
ports:
- '5000:5000'
depends_on:
- mongo

37. How do you use Axios for fetching data from a Node.js API in React?

Answer:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState([]);useEffect(() => {
axios.get(‘http://localhost:5000/products’)
.then(res => setData(res.data))
.catch(err => console.log(err));
}, []);

return <ul>{data.map(p => <li key={p._id}>{p.name}</li>)}</ul>;
}

38. Implement file upload functionality using Multer in Express.js.

Answer:

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

39. How would you implement pagination in MongoDB using Mongoose?

app.get('/products', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = 10;
const skip = (page - 1) * limit;
const products = await Product.find().skip(skip).limit(limit);
res.send(products);
});

40. How do you secure Express routes using middleware?

Answer:

const isAuthenticated = (req, res, next) => {
if (req.user) next();
else res.sendStatus(401);
};
app.get(‘/dashboard’, isAuthenticated, (req, res) => {
res.send(‘Secure data’);
});

41. How do you handle errors globally in an Express app?

Answer:

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send({ error: err.message });
});

42. How would you create a protected route in React using React Router?

Answer:

import { Navigate } from 'react-router-dom';

function PrivateRoute({ children }) {
const isAuthenticated = !!localStorage.getItem(‘token’);
return isAuthenticated ? children : <Navigate to=“/login” />;
}

43. How do you structure a scalable MERN app project?

Answer:

/client
/server
/controllers
/routes
/models
/middleware
server.js

44. Write a schema and model in Mongoose for a User.

Answer:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String,
}, { timestamps: true });

module.exports = mongoose.model(‘User’, userSchema);

45. How would you handle real-time updates using Socket.IO in a MERN app?

Answer (Backend):

const http = require('http').createServer(app);
const io = require('socket.io')(http);
io.on(‘connection’, socket => {
console.log(‘User connected’);
socket.on(‘message’, msg => {
io.emit(‘message’, msg);
});
});

Frontend:

import io from 'socket.io-client';
const socket = io('http://localhost:5000');
socket.on(‘message’, msg => console.log(msg));

46. What is debouncing and how do you implement it in React?

Answer:

function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
47. How do you update nested state in React?

Answer:

setState(prev => ({
...prev,
profile: {
...prev.profile,
name: 'John'
}
}));

48. How do you perform validation in Mongoose models?

Answer:

const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
match: /.+\@.+\..+/
}
});

49. How do you use useReducer for complex state in React?

Answer:

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

50. What is the use of Helmet in Express apps?

Answer:

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

 

 

 

 

Calculate the price of your order

You will get a personal manager and a discount.
We'll send you the first draft for approval by at
Total price:
$0.00