100 MERN Stack Interview Questions & Answers
From JavaScript fundamentals to full-stack system design — a complete, interview-ready walkthrough of MongoDB, Express, React and Node.js.
What You’ll Cover
Level: Beginner → Intermediate → Advanced
Technologies covered:
MERN & JavaScript Fundamentals
What is the MERN Stack?
MERN stands for:
- MongoDB – database
- Express.js – backend web framework
- React.js – frontend UI library
- Node.js – JavaScript runtime used on the server
A typical flow is:
React UI → HTTP request → Express/Node API → MongoDB → API response → React UI
One major advantage is that JavaScript can be used throughout most of the application.
What happens when a user submits a form in a MERN application?
Suppose a user submits a registration form.
- React captures the form data.
- Client-side validation may run.
- React sends an HTTP request such as
POST /api/users - Express matches the route.
- Middleware may validate or authenticate the request.
- The controller processes it.
- Mongoose communicates with MongoDB.
- MongoDB saves the user.
- Express sends an HTTP response.
- React updates the interface.
A good interview answer should also mention what happens when validation or database operations fail.
What is the difference between var , let , and const ?
var is function-scoped, while let and const are block-scoped.
if (true) {
let x = 10;
}
console.log(x); // ReferenceError
const prevents reassignment:
const age = 20;
age = 21; // Error
However, objects declared with const can still be modified internally:
const user = { name: "Ali" };
user.name = "Rahul";
Modern JavaScript generally prefers const by default and let when reassignment is required.
What is the difference between == and === ?
== performs type coercion.
5 == "5"; // true
=== checks value and type.
5 === "5"; // false
In production JavaScript, === is generally preferred because its behavior is more predictable.
What are primitive and reference data types?
Primitive values include:
- string
- number
- boolean
- bigint
- symbol
- undefined
- null
Objects, arrays, and functions are reference values.
Example:
let a = { name: "John" };
let b = a;
b.name = "Sam";
console.log(a.name); // Sam
Both variables refer to the same object.
What is a closure?
A closure occurs when a function remembers variables from its outer scope even after the outer function has finished executing.
function counter() {
let count = 0;
return function () {
count++;
return count;
};
}
const increment = counter();
increment(); // 1
increment(); // 2
Closures are frequently encountered in React hooks, event handlers, callbacks and module patterns.
What is hoisting?
JavaScript processes declarations before code execution.
For example:
console.log(x);
var x = 10;
behaves roughly like:
var x;
console.log(x);
x = 10;
The result is undefined.
let and const are also hoisted internally but cannot be accessed before initialization because they remain in the temporal dead zone.
What is the difference between synchronous and asynchronous JavaScript?
Synchronous code executes sequentially.
console.log("A");
console.log("B");
Asynchronous operations can complete later without requiring the program to remain blocked waiting for them.
console.log("A");
setTimeout(() => {
console.log("B");
}, 1000);
console.log("C");
Output:
A
C
B
HTTP requests, timers, file operations and database access commonly involve asynchronous behavior.
What is a Promise?
A Promise represents the eventual result of an asynchronous operation.
It can be:
- pending
- fulfilled
- rejected
Example:
fetch("/api/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Promises help organize asynchronous operations and avoid deeply nested callbacks.
What is async/await ?
async/await provides cleaner syntax for working with Promises.
async function getUsers() {
try {
const response = await fetch("/api/users");
const users = await response.json();
console.log(users);
} catch (error) {
console.error(error);
}
}
await pauses execution of that async function until the Promise settles; it does not mean the entire Node.js process becomes blocked.
What is destructuring?
Destructuring extracts values from arrays or objects.
Object example:
const user = {
name: "Rahul",
age: 22
};
const { name, age } = user;
Array example:
const numbers = [10, 20];
const [a, b] = numbers;
It is extremely common in React:
const [count, setCount] = useState(0);
What are spread and rest operators?
Both use ..., but their purpose depends on context.
Spread expands values:
const oldUser = { name: "Aman", age: 20 };
const newUser = {
...oldUser,
age: 21
};
Rest collects remaining values:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
Explain map() , filter() and reduce() .
map() transforms every element.
[1, 2, 3].map(x => x * 2);
// [2, 4, 6]
filter() selects elements.
[1, 2, 3, 4].filter(x => x > 2);
// [3, 4]
reduce() combines values.
[1, 2, 3].reduce((total, x) => total + x, 0);
// 6
These are frequently asked because React code relies heavily on immutable array operations.
What is shallow copy versus deep copy?
A shallow copy copies the first level but nested objects can remain shared.
const user = {
name: "John",
address: {
city: "Kolkata"
}
};
const copy = { ...user };
copy.address.city = "Delhi";
console.log(user.address.city); // Delhi
For appropriate serializable data, modern JavaScript provides:
const copy = structuredClone(user);
Deep copying should not be done blindly because application objects may contain non-cloneable or specialized values.
Why is immutability important in React?
React often relies on reference changes to detect updates efficiently.
Wrong:
user.name = "Rahul";
setUser(user);
Better:
setUser({
...user,
name: "Rahul"
});
Creating a new object allows React and related libraries to recognize that data has changed.
React Interview Questions
What is React?
React is a JavaScript library for building user interfaces using reusable components.
A React application is typically divided into components such as:
App
├── Navbar
├── Sidebar
├── ProductList
│ └── ProductCard
└── Footer
Each component can manage its own rendering logic and state.
What is JSX?
JSX allows markup-like syntax inside JavaScript.
const element = <h1>Hello Student</h1>;
JSX is transformed into JavaScript during the build process.
Expressions can be embedded using braces:
<h1>Hello {user.name}</h1>
What is a React component?
A component is a reusable piece of UI.
function Welcome({ name }) {
return <h1>Welcome {name}</h1>;
}
Usage:
<Welcome name="Rahul" />
Modern React applications predominantly use functional components.
What are props?
Props allow a parent component to pass information to a child component.
function Student({ name }) {
return <p>{name}</p>;
}
<Student name="Aman" />
A component should treat props as read-only.
What is state?
State represents data owned by a component that may change over time.
const [count, setCount] = useState(0);
Updating state:
setCount(count + 1);
causes React to schedule another render.
Props vs state?
Props
- provided by parent
- read-only from the receiving component’s perspective
- used for component communication
State
- managed by the component or state layer
- changes over time
- causes rendering updates
Example:
<Product price={500} />
price is a prop.
A quantity selected inside Product may be state.
What is useState ?
useState adds state to functional components.
const [name, setName] = useState("");
Example:
<input
value={name}
onChange={e => setName(e.target.value)}
/>
Changing the state schedules a re-render.
What is useEffect ?
useEffect is used to synchronize a component with systems outside React, such as:
- APIs
- subscriptions
- timers
- browser APIs
Example:
useEffect(() => {
fetchUsers();
}, []);
A common interview mistake is saying that useEffect should be used for every calculation. Pure values that can be calculated during rendering usually do not require an effect.
Explain the dependency array in useEffect .
useEffect(() => {
console.log("runs after every relevant render");
});
No dependency array means the effect runs after every render.
useEffect(() => {
loadData();
}, []);
An empty dependency array means the effect is established once for that mount.
useEffect(() => {
loadUser(userId);
}, [userId]);
This effect re-runs when userId changes.
Dependencies should represent reactive values used by the effect.
Why can useEffect create an infinite loop?
Example:
useEffect(() => {
setCount(count + 1);
}, [count]);
Updating count causes the effect to run again, which updates count again.
This produces a loop.
You must rethink the state/effect relationship rather than simply removing dependencies to silence the problem.
What is useRef ?
useRef stores a mutable value that survives renders without causing a new render when changed.
Common uses include:
- accessing DOM nodes
- storing timers
- keeping mutable instance-like values
Example:
const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus
</button>
What is useMemo ?
useMemo can cache a calculated value between renders.
const sortedUsers = useMemo(() => {
return expensiveSort(users);
}, [users]);
It is primarily a performance optimization.
Do not add it automatically to every calculation because memoization itself has cost and complexity.
What is useCallback ?
useCallback can preserve a function reference between renders until dependencies change.
const handleDelete = useCallback(id => {
deleteUser(id);
}, []);
It may be useful when passing callbacks to memoized children or when a stable callback reference is required.
Difference between useMemo and useCallback ?
useMemo caches a calculated value.
const value = useMemo(() => calculate(), [data]);
useCallback caches a function reference.
const fn = useCallback(() => calculate(), [data]);
Neither should be used blindly.
What is the Virtual DOM?
React represents UI structure in memory.
When state changes, React renders a new description of the UI and reconciles it with the previous one to determine the required host DOM updates.
The important interview concept is not simply “Virtual DOM makes React fast,” but reconciliation and minimizing necessary DOM work.
What is reconciliation?
Reconciliation is React’s process for determining how a new rendered tree relates to the previous one.
React uses factors such as:
- element type
- component position
- keys
to preserve, update or replace elements and component state.
Why are keys required when rendering lists?
Keys help React identify items across updates.
users.map(user => (
<User key={user._id} user={user} />
))
Good keys should be stable and unique among siblings.
Avoid array indexes when list items can be inserted, removed or reordered because incorrect identity can lead to UI/state bugs.
Controlled vs uncontrolled components?
A controlled form field uses React state:
const [email, setEmail] = useState("");
<input
value={email}
onChange={e => setEmail(e.target.value)}
/>
An uncontrolled field can keep its value in the DOM and may be read using a ref.
Controlled inputs provide more direct control over validation and form behavior, although both approaches have valid use cases.
What is lifting state up?
When sibling components need shared data, state can be moved to their nearest common parent.
Instead of:
Component A → separate state
Component B → separate state
use:
Parent
|
| shared state
|
A B
The parent then passes data and callbacks through props.
What is Context API?
Context allows data to be made available to descendant components without passing it manually through every intermediate component.
Typical examples include:
- logged-in user
- theme
- locale
const AuthContext = createContext(null);
Context is useful, but putting frequently changing large application state into one context can create unnecessary renders and difficult architecture.
Context API vs Redux?
Context is useful for distributing values through a component tree.
Redux provides a more structured state-management architecture including:
- centralized store
- predictable updates
- middleware support
- excellent debugging tools
- selectors
- Redux Toolkit conventions
For small applications, Context plus local state may be enough.
For complex shared state and workflows, a dedicated state-management solution can become useful.
What is Redux Toolkit?
Redux Toolkit is the recommended approach for modern Redux development.
Example:
const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0
},
reducers: {
increment(state) {
state.value++;
}
}
});
It reduces traditional Redux boilerplate and provides standard patterns for store setup and reducers.
What is React.memo?
React.memo can prevent a component from rendering again when its props are unchanged according to React’s comparison.
const UserCard = React.memo(function UserCard({ user }) {
return <div>{user.name}</div>;
});
It is a performance tool, not something that should automatically wrap every component.
How do you optimize a slow React application?
First identify the actual bottleneck.
Possible strategies include:
- reduce unnecessary renders
- move state closer to where it is needed
- paginate large datasets
- virtualize very large lists
- memoize expensive calculations where beneficial
- code-split large bundles
- lazy-load routes/components
- optimize images
- debounce expensive user-triggered operations
- cache API responses where appropriate
Use profiling instead of guessing.
What is code splitting?
Code splitting prevents the entire JavaScript application from needing to load as one large bundle.
Example:
const Admin = lazy(() => import("./Admin"));
Then:
<Suspense fallback={<Loading />}>
<Admin />
</Suspense>
This can improve initial loading performance for larger applications.
Node.js & Express
What is Node.js?
Node.js is a JavaScript runtime that allows JavaScript to execute outside the browser.
It is commonly used for:
- REST APIs
- real-time servers
- background services
- CLI tools
- streaming applications
Node.js uses an event-driven architecture and is particularly effective for I/O-heavy workloads.
Is Node.js single-threaded?
JavaScript execution in a typical Node.js process primarily runs on one event-loop thread.
However, saying “Node is completely single-threaded” is inaccurate.
Node also uses:
- operating-system asynchronous I/O
- a libuv worker pool for certain operations
- Worker Threads when developers explicitly use them
The important distinction is between the JavaScript event loop and the underlying runtime’s ability to perform work concurrently.
What is the Node.js event loop?
The event loop allows Node.js to coordinate asynchronous operations without creating a separate JavaScript thread for every request.
Consider:
console.log("start");
setTimeout(() => {
console.log("timer");
}, 0);
console.log("end");
Output:
start
end
timer
Understanding the event loop becomes especially important when debugging latency and blocking operations.
What is blocking code?
Blocking code prevents the event-loop thread from processing other JavaScript work.
Example:
const data = fs.readFileSync("large-file.txt");
During that synchronous read, that thread cannot process other application JavaScript.
For server request paths, asynchronous alternatives are often preferred:
const data = await fs.promises.readFile("large-file.txt");
Why is CPU-intensive work problematic in Node.js?
Long CPU-heavy JavaScript operations can block the event loop.
Examples include:
- huge synchronous loops
- heavy image processing
- CPU-intensive transformations
- certain cryptographic workloads
Options include:
- Worker Threads
- separate worker services
- job queues
- specialized external services
depending on the problem.
What is Express.js?
Express is a minimal web framework for Node.js commonly used to build APIs and web servers.
Example:
const express = require("express");
const app = express();
app.get("/users", (req, res) => {
res.json([]);
});
app.listen(3000);
Express provides routing and middleware abstractions around Node’s HTTP capabilities.
What is middleware in Express?
Middleware runs during the request-response cycle.
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
Usage:
app.use(logger);
Middleware can:
- execute code
- inspect requests
- modify request/response objects
- authenticate users
- validate input
- end a response
- pass control onward
Middleware order matters. Express’s official documentation describes Express applications as a series of middleware calls in the request-response cycle.
What happens if middleware doesn’t call next() ?
If the middleware does not:
- call
next(), or - send/end the response,
the request can remain unfinished.
Incorrect:
app.use((req, res, next) => {
console.log("request");
});
Correct:
app.use((req, res, next) => {
console.log("request");
next();
});
What is the difference between app.use() and app.get() ?
app.get() handles GET requests for a matching route.
app.get("/users", handler);
app.use() mounts middleware or routers and is not restricted to only GET.
app.use("/api/users", userRouter);
Why use express.Router() ?
Routers allow APIs to be split into modules.
const router = express.Router();
router.get("/", getUsers);
router.post("/", createUser);
module.exports = router;
Then:
app.use("/api/users", userRouter);
This is preferable to putting hundreds of routes in one server file.
What is MVC architecture?
MVC commonly separates responsibilities into:
Model
Database/data behavior.
View
UI/presentation.
Controller
Request/business handling.
In many MERN APIs you may see:
routes/
controllers/
models/
services/
middleware/
Production architecture often extends beyond strict textbook MVC.
What is a REST API?
REST-style APIs typically model resources using HTTP methods and URLs.
Example:
GET /api/products
GET /api/products/:id
POST /api/products
PATCH /api/products/:id
DELETE /api/products/:id
HTTP method plus resource URL communicates the intended operation.
PUT vs PATCH?
Conceptually:
PUT commonly represents replacing the resource representation.
PATCH represents partial modification.
Example:
PATCH /users/123
{
"name": "Rahul"
}
Only the specified information needs to change.
What important HTTP status codes should a MERN developer know?
Common codes include:
200 OK
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
422 Unprocessable Content
429 Too Many Requests
500 Internal Server Error
Do not return 200 for every possible result.
What is CORS?
CORS stands for Cross-Origin Resource Sharing.
Browsers apply same-origin security rules.
If React runs on:
https://app.example.com
and the API runs on:
https://api.example.com
the API needs appropriate CORS configuration for browser requests.
Example:
app.use(cors({
origin: "https://app.example.com",
credentials: true
}));
Using * indiscriminately is not appropriate when credentials and restricted origins are required.
How should errors be handled in Express?
A production application should normally centralize error handling rather than repeating similar response logic in every route.
Example:
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({
message: err.message || "Internal server error"
});
});
Production responses should avoid exposing stack traces or internal implementation details.
Authentication vs authorization?
Authentication
Determines who the user is.
Example:
Is this Rahul?
Authorization
Determines what that user may do.
Example:
Can Rahul delete this product?
A user can be authenticated but still not authorized for an administrative operation.
What is JWT?
JWT stands for JSON Web Token.
It consists of three encoded sections:
header.payload.signature
A server can verify the signature to determine whether the token has been altered and validate its claims.
JWT contents are encoded, not automatically encrypted.
Therefore sensitive information should not simply be placed in a JWT payload assuming it is secret.
Where should authentication tokens be stored?
There is no single answer for every architecture.
For browser-based applications, teams frequently use carefully configured HttpOnly secure cookies for authentication because client-side JavaScript cannot directly read an HttpOnly cookie.
Cookie-based authentication then requires proper attention to:
SecureSameSite- HTTPS
- CSRF protection where applicable
- CORS
- cookie domain/path
Storing long-lived sensitive credentials in localStorage increases exposure if malicious JavaScript executes through an XSS vulnerability.
How do you hash passwords?
Passwords should not be stored in plaintext.
Applications typically use a password hashing algorithm such as:
- Argon2
- bcrypt
- scrypt
Example conceptually:
const passwordHash = await bcrypt.hash(password, 12);
On login:
const valid = await bcrypt.compare(password, user.passwordHash);
Hashing is not the same as reversible encryption.
What is rate limiting?
Rate limiting restricts how many requests a client can make during a period.
Example:
100 requests / 15 minutes
It is particularly useful for:
- login endpoints
- OTP endpoints
- password-reset endpoints
- expensive APIs
- public APIs
It reduces abuse but should not be considered the only security control.
What are environment variables?
Environment variables hold configuration that differs between environments.
Examples:
DATABASE_URL
JWT_SECRET
PORT
REDIS_URL
Do not hard-code production credentials:
const password = "production-password";
Secrets should be managed through an appropriate secret/configuration system.
What are streams in Node.js?
Streams process data incrementally instead of loading everything into memory first.
Examples include:
- large files
- video
- network responses
- exports
Instead of reading a 2 GB file completely into memory, an application can process it chunk by chunk.
Main stream categories include:
- Readable
- Writable
- Duplex
- Transform
What are buffers in Node.js?
A Buffer represents binary data.
Examples include:
- file contents
- images
- network packets
- encoded binary protocols
const buffer = Buffer.from("Hello");
Buffers matter when working below the string/object abstraction level.
What are Worker Threads?
Worker Threads allow JavaScript work to run on additional threads within a Node.js process.
They are useful for certain CPU-intensive tasks.
They are not necessary for ordinary asynchronous database or HTTP operations because those are primarily I/O-bound.
MongoDB & Mongoose
What is MongoDB?
MongoDB is a document-oriented database.
A document may look like:
{
"_id": "...",
"name": "Rahul",
"email": "rahul@example.com",
"skills": ["React", "Node"]
}
Documents are stored in collections.
MongoDB stores BSON internally, which supports additional data types beyond plain JSON.
SQL vs MongoDB?
Typical relational terminology:
Database
Table
Row
Column
MongoDB terminology:
Database
Collection
Document
Field
Relational databases emphasize tables and relations.
MongoDB uses documents and supports embedding/reference patterns.
The correct choice depends on data access patterns, consistency requirements, team expertise and system requirements.
What is BSON?
BSON stands for Binary JSON.
MongoDB uses BSON to represent documents and support types such as:
- ObjectId
- Date
- binary data
- Decimal128
that ordinary JSON does not natively represent in the same way.
What is _id in MongoDB?
Every MongoDB document has an _id field that uniquely identifies it within the collection.
MongoDB can automatically generate an ObjectId:
ObjectId("...")
Applications can also use custom _id values when appropriate.
What is Mongoose?
Mongoose is an Object Data Modeling library commonly used with Node.js and MongoDB.
It provides features such as:
- schemas
- models
- validation
- middleware/hooks
- population
- query helpers
Example:
const userSchema = new mongoose.Schema({
name: String,
email: {
type: String,
required: true,
unique: true
}
});
Does MongoDB have no schema?
“MongoDB is schema-less” is an oversimplification.
MongoDB provides a flexible document model where documents in the same collection do not have to be identical.
However, real applications still need data design and often enforce structure through:
- application code
- Mongoose validation
- MongoDB schema validation
Flexible schema does not mean “no data model.”
Embedding vs referencing?
Embedding:
{
"name": "Rahul",
"addresses": [
{
"city": "Kolkata"
}
]
}
Referencing:
{
"userId": "123"
}
Choose based on access patterns.
Embedding is useful when related data:
- belongs closely together
- is normally read together
- remains bounded
Referencing may be preferable when:
- related collections grow independently
- data is shared
- embedded arrays could grow without practical bounds
What is populate() in Mongoose?
populate() resolves referenced documents.
Example:
const orders = await Order
.find()
.populate("user");
It provides convenience similar to resolving relations at the application/ODM level.
However, excessive population can increase database work and application latency.
What is an index?
An index is a data structure used by MongoDB to find documents more efficiently for supported query patterns.
Example:
db.users.createIndex({ email: 1 });
Without a useful index, MongoDB may need to scan many or all documents.
MongoDB’s documentation emphasizes building indexes around common query patterns. It also warns that indexes have write/storage costs because inserts and updates may need to maintain them.
What is a compound index?
A compound index contains multiple fields.
db.orders.createIndex({
userId: 1,
createdAt: -1
});
It may efficiently support a query such as:
db.orders.find({
userId: userId
}).sort({
createdAt: -1
});
Field order matters when designing compound indexes.
Can too many indexes be harmful?
Yes.
Indexes improve certain reads, but they also consume:
- storage
- memory/cache resources
- write processing
Every insert/update may require relevant indexes to be updated.
Therefore, “index every field” is poor database design.
MongoDB explicitly notes that excessive indexing can degrade write performance.
What is the MongoDB aggregation pipeline?
Aggregation processes documents through a sequence of stages.
Example:
db.orders.aggregate([
{
$match: {
status: "paid"
}
},
{
$group: {
_id: "$customerId",
total: {
$sum: "$amount"
}
}
}
]);
Common stages include:
$match
$project
$group
$sort
$limit
$unwind
$lookup
$match vs $project ?
$match filters documents.
{
$match: {
status: "active"
}
}
$project controls/transforms output fields.
{
$project: {
name: 1,
email: 1
}
}
They solve different problems.
What is $lookup ?
$lookup combines related information from another collection.
Example:
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
}
It provides join-like functionality.
However, data modeling should not automatically copy relational-database design and rely on large numbers of joins.
What is $unwind ?
$unwind converts each array element into a separate pipeline document.
Input:
{
"name": "Rahul",
"skills": ["React", "Node"]
}
After unwinding skills, conceptual output becomes:
{
"name": "Rahul",
"skills": "React"
}
and:
{
"name": "Rahul",
"skills": "Node"
}
find() vs findOne() ?
find() returns a cursor representing matching documents.
User.find({ active: true });
findOne() returns one matching document or null.
User.findOne({
email: "rahul@example.com"
});
Use the operation that best matches the expected cardinality.
What is pagination?
Pagination prevents APIs from returning enormous collections at once.
Simple offset pagination:
const page = 3;
const limit = 20;
const users = await User.find()
.skip((page - 1) * limit)
.limit(limit);
For very large/changing datasets, cursor-based pagination can be more scalable and consistent than very large skip() offsets.
What is a MongoDB transaction?
Transactions allow multiple database operations to behave as one atomic unit.
Example business case:
Create order
Decrease inventory
Record payment state
If these operations must succeed or fail together, a transaction may be appropriate.
Transactions are useful but should not replace good document modeling.
What is replication?
MongoDB replication maintains copies of data across multiple servers using replica sets.
A replica set includes nodes that maintain replicated data.
Replication supports:
- redundancy
- failover
- higher availability
It should not be confused with sharding.
Replication vs sharding?
Replication
Primarily improves availability and redundancy by maintaining copies of data.
Sharding
Distributes data across multiple shards to scale data/storage/workload horizontally.
Large systems can use both.
Full-Stack, Security & Advanced
Design a secure MERN login flow.
A reasonable login flow is:
- React sends credentials over HTTPS.
- Express validates input.
- Server finds the user.
- Password hash is verified.
- Server establishes an authenticated session/token.
- Browser receives appropriately protected authentication state.
- Protected routes verify authentication.
- Authorization rules check permissions.
Additional controls may include:
- login rate limiting
- account lockout/risk rules
- secure cookies
- CSRF protection where applicable
- short-lived access credentials
- refresh-token/session rotation
- security logging
- MFA for appropriate systems
How would you protect an admin route?
Do not rely only on hiding the admin button in React.
The backend must enforce authorization.
Example:
function requireAdmin(req, res, next) {
if (req.user.role !== "admin") {
return res.status(403).json({
message: "Forbidden"
});
}
next();
}
Then:
router.delete(
"/users/:id",
authenticate,
requireAdmin,
deleteUser
);
Frontend permissions improve UX; backend permissions provide actual security.
What is XSS?
Cross-Site Scripting occurs when attacker-controlled content is executed as JavaScript in another user’s browser.
Example danger:
<script>
stealCookies()
</script>
Mitigations include:
- safely rendering/escaping user content
- avoiding unsafe HTML injection
- sanitizing HTML when HTML input is genuinely required
- Content Security Policy
- secure cookie design
In React, ordinary text interpolation is escaped, but unsafe mechanisms such as arbitrary HTML injection still require care.
What is CSRF?
Cross-Site Request Forgery tricks a user’s browser into making an unwanted authenticated request to another application.
It is especially relevant when authentication credentials are automatically sent by the browser, such as cookies.
Defenses may include:
- SameSite cookie settings
- CSRF tokens
- checking request origin
- appropriate application architecture
XSS and CSRF are different vulnerabilities.
How should API input be validated?
Never trust browser validation alone.
The server must validate:
- data types
- required fields
- allowed values
- string length
- number ranges
- IDs
- file types/sizes
- application-specific rules
Libraries such as:
Zod
Joi
express-validator
can help.
Validation belongs at trust boundaries.
How do you prevent duplicate email registrations?
Application code can check:
const existing = await User.findOne({ email });
but that alone is vulnerable to race conditions.
A database-level unique index should enforce uniqueness:
db.users.createIndex(
{ email: 1 },
{ unique: true }
);
The server should then handle duplicate-key errors appropriately.
This is a strong interview answer because it distinguishes application validation from database guarantees.
Your /products API becomes slow with one million records. What do you check?
I would investigate before optimizing.
Check:
- query shape
- MongoDB execution plan
- missing/incorrect indexes
- returned fields
- pagination
- expensive sorting
- aggregation stages
- document size
- excessive
populate() - application/database latency
- network payload size
For MongoDB:
db.products.find({
category: "mobile"
}).explain("executionStats");
Look for excessive documents examined compared with documents returned.
How would you build search suggestions without sending a request for every keystroke?
Use debouncing.
Instead of:
r
ra
rah
rahu
rahul
causing five immediate requests, wait briefly after typing stops.
Example concept:
useEffect(() => {
const timer = setTimeout(() => {
search(query);
}, 300);
return () => clearTimeout(timer);
}, [query]);
Production search may also require:
- request cancellation
- caching
- minimum query length
- indexed search
- dedicated search infrastructure at larger scale
Debouncing vs throttling?
Debouncing
Executes after events stop for a period.
Useful for:
Search boxes
Form validation
Autosave
Throttling
Limits execution to at most once during an interval.
Useful for:
scroll handlers
resize handlers
high-frequency event tracking
How would you handle 100,000 concurrent users?
There is no single setting called “support 100,000 users.”
I would evaluate each layer.
Potential architecture:
CDN
↓
Load Balancer
↓
Multiple Node.js instances
↓
Cache
↓
MongoDB cluster
Consider:
- stateless API instances
- horizontal scaling
- connection pooling
- database indexes
- Redis caching where appropriate
- queues for asynchronous work
- CDN for static assets
- pagination
- rate limiting
- monitoring
- autoscaling
- database replication/sharding when justified
The first step should still be measuring the application’s actual bottleneck.
When should Redis be added to a MERN architecture?
Common use cases include:
Caching
GET product → Redis hit → return quickly
Session storage
Useful when multiple application servers share sessions.
Rate limiting
Counters can be shared across API instances.
Queue infrastructure
Redis-backed queue systems can support background jobs.
Short-lived data
Examples:
OTP
temporary token
cached leaderboard
Redis should solve a demonstrated problem rather than being added because it is fashionable.
What is a message/job queue and why use one?
A queue moves work out of the immediate request path.
Imagine:
POST /orders
The application may need to:
- create the order
- email the customer
- generate an invoice
- resize images
- send notifications
The API should not necessarily make the user wait for every secondary task.
Instead:
API
↓
Queue
↓
Worker
Technologies can include:
- BullMQ
- RabbitMQ
- Kafka
- cloud queue services
depending on requirements.
How would you test a MERN application?
Testing should happen at multiple levels.
Unit tests
Test individual functions/components.
Example tools:
Vitest
Jest
API/integration tests
Test actual route behavior and component interactions.
Example:
Supertest
React component tests
Example:
React Testing Library
End-to-end tests
Simulate real user workflows.
Examples:
Playwright
Cypress
A strong test suite focuses on important behavior rather than trying to maximize a coverage percentage without purpose.
Explain optimistic UI updates.
Normally:
User clicks Like
→ request server
→ server responds
→ UI changes
Optimistic UI:
User clicks Like
→ UI changes immediately
→ request server
→ rollback if request fails
This creates a faster-feeling UI.
Example:
setLiked(true);
try {
await api.likePost(postId);
} catch (error) {
setLiked(false);
}
It is appropriate when failure is relatively uncommon and rollback behavior is manageable.
System-design question: How would you design an e-commerce application using MERN?
A strong interview answer should describe the whole system rather than saying:
React frontend, Node backend, MongoDB database.
Frontend
React application:
Home
Products
Search
Product Details
Cart
Checkout
Orders
Account
Admin
State could be divided into:
local component state
server-state/cache layer
authentication state
shopping-cart state
Backend
Node + Express:
/api/auth
/api/users
/api/products
/api/categories
/api/cart
/api/orders
/api/payments
/api/reviews
/admin
Suggested layering:
Routes
↓
Validation / Auth Middleware
↓
Controllers
↓
Services
↓
Repository / Data Access
↓
MongoDB
MongoDB collections
Possible collections:
users
products
categories
orders
reviews
coupons
inventory
Product indexes
Depending on query patterns:
{ slug: 1 }
{ categoryId: 1, createdAt: -1 }
{ sku: 1 }
Search may eventually require MongoDB search features or dedicated search infrastructure depending on scale and requirements.
Authentication
Use secure authentication with:
- password hashing
- short-lived authentication credentials/sessions
- secure cookies where appropriate
- role/permission checks
Payments
Never trust a frontend message saying:
payment = successful
Payment state must be verified using the payment provider’s trusted server-side response/webhook/signature mechanisms.
Inventory
Inventory changes require careful concurrency handling.
Two customers should not both successfully purchase the last unit.
Depending on architecture, this may involve:
- atomic updates
- conditional updates
- transactions
- reservations
Performance
Use:
CDN
image optimization
pagination
database indexes
appropriate caching
connection pooling
lazy loading
code splitting
Background work
Queue tasks such as:
emails
invoice generation
notifications
image processing
reports
Security
Include:
HTTPS
validation
authorization
rate limiting
secure headers
XSS defenses
CSRF defenses where required
safe file uploads
secret management
logging
dependency updates
Deployment
Typical architecture:
CDN
|
React App
|
Load Balancer
|
-----------------------
| | |
Node Node Node
| | |
-------- Redis --------
|
MongoDB
|
Job Queue
|
Workers
Monitoring
Production systems should track:
API latency
error rates
CPU
memory
event-loop delay
database latency
slow queries
queue backlog
authentication failures
payment failures
The strongest interview answer explains why each component exists and what problem it solves.
15 Follow-Up Questions Interviewers May Ask
After the 100 core questions, students should also prepare for questions such as:
- Explain your MERN project architecture from frontend to database.
- What was the hardest production bug you fixed?
- Why did you choose MongoDB instead of PostgreSQL/MySQL?
- How did you implement authentication?
- How would you invalidate a stolen access token?
- What happens if MongoDB becomes unavailable?
- How do you handle race conditions?
- How do you prevent overselling inventory?
- How do you identify a slow MongoDB query?
- How would you deploy a MERN application?
- How do you store application secrets?
- How would you debug a Node server using 100% CPU?
- How would you debug unnecessary React renders?
- How would you handle millions of records?
- What would you redesign in your current project if traffic increased 100×?
How to Prepare These 100 Questions
Do not memorize paragraphs word-for-word.
For each question, learn three layers:
Layer 1 — Definition
Be able to explain the concept in one or two sentences.
Layer 2 — Example
Be able to show a small example.
For example:
useEffect(() => {
fetchUsers();
}, []);
Layer 3 — Production reasoning
Be ready to answer:
Why would you use this?
When would you avoid it?
What can go wrong?
How did you use it in your project?
That third layer is usually what separates someone who has completed tutorials from someone who understands application development.
Most Important Topics for a MERN Interview
Students should be particularly strong in:
JavaScript
React
Node.js
Express
MongoDB
Real Full-Stack Development
The Final Interview Rule
When an interviewer asks:
“Have you used this?”
avoid answering only:
“Yes, I know it.”
A stronger response is:
“Yes. In my project I used it for ____. The reason was ____. One issue I encountered was ____, and I solved it by ____.”
That turns theoretical knowledge into evidence of engineering understanding.
