Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
It's four JavaScript technologies working together: MongoDB stores the data, Express handles server routes, React builds the user interface, and Node.js runs the server code. The big advantage is one language across the whole app.
It handles many connections at once without creating a thread for each, so it's efficient for APIs, chat apps and anything I/O-heavy. It's less suited to heavy CPU work like video encoding.
Node runs your code on a single thread. When it hits slow work such as a database call, it hands it off and keeps going. When the result is ready, the callback is queued and the event loop runs it. It works like a waiter who takes many orders without standing at the kitchen door.
A function that sits between the request and the final response. It can read or change req and res, then call next() to pass control on. Logging, authentication and parsing JSON are typical uses.
It treats data as resources with URLs, like /users/5, and uses HTTP methods for actions: GET reads, POST creates, PUT/PATCH updates, DELETE removes. It's also stateless, so each request carries everything the server needs.
MongoDB stores flexible JSON-like documents in collections instead of rigid rows in tables. You don't need a fixed schema up front, and related data can live inside a single document. SQL is stronger for complex joins and strict relationships.
It gives you schemas, validation, middleware hooks and convenient query methods. MongoDB itself is schema-less, and Mongoose brings in structure so your data stays consistent.
Without an index, MongoDB scans every document to answer a query. An index works like a book's index, letting it jump straight to matches. The trade-off is extra storage and slightly slower writes.
Embed when the data is small and always read together, like addresses inside a user. Reference when the data is large, shared, or changes independently, like orders pointing to a product ID.
React keeps a lightweight copy of the UI in memory. When state changes, it builds a new copy, compares it with the old one, and updates only the parts of the real DOM that differ. That's much cheaper than redrawing everything.
A syntax that lets you write HTML-looking markup inside JavaScript. A build tool converts it into regular function calls, so the browser never sees JSX.
Props are inputs passed down from a parent and shouldn't be modified by the child. State is data a component owns and can change, and changing it triggers a re-render.
It runs side effects after rendering, such as fetching data, setting timers or subscribing to events. The dependency array controls when it runs, and a returned cleanup function handles teardown.
useMemo remembers the result of an expensive calculation, and useCallback remembers a function so its identity stays stable between renders. Use them when you've measured a real slowdown, not by default.
Keys give each item a stable identity, so React can tell which items were added, moved or removed. Using array indexes as keys can cause wrong updates when the list order changes.
A form input whose value lives in React state. The input displays the state and every change updates it, so React is always the single source of truth.
Context is built in and fine for light shared data like theme or logged-in user. Redux suits larger apps with complex state, since it adds predictable updates and good debugging tools. Many apps never need Redux.
After login, the server signs a token containing the user's identity and sends it back. The client attaches it to later requests, and the server verifies the signature instead of storing a session.
Storing plain passwords is dangerous if the database leaks. A library like bcrypt turns each password into a salted, one-way hash, so the server can verify a login without ever knowing the original.
A browser rule that blocks a page from calling a different origin unless that server allows it. In Express you enable it with the cors package and list which origins may connect.
They keep secrets like database URLs and JWT keys out of your source code. Put them in a .env file, load it with dotenv, and never commit it to Git.
They're three ways to handle asynchronous work. Callbacks can nest into a mess, promises chain results more cleanly, and async/await lets you write async code that reads top to bottom.
PUT replaces the entire resource, while PATCH changes only the fields you send. For a small edit like updating an email, PATCH is the better fit.
200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found and 500 Server Error. Using them correctly makes an API much easier to debug.
With client-side rendering, the browser downloads JavaScript and builds the page, as in a plain React app. With server-side rendering, the server sends ready-made HTML, which helps SEO and first load. Frameworks like Next.js provide it.
Initialize Express app, configure JSON middleware, define root endpoint and listen on port.
const express = require("express");
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.json({ message: "Server is running" });
});
app.listen(5000, () => console.log("Listening on port 5000"));
Create Express Router handling GET, POST, PATCH, and DELETE operations.
const express = require("express");
const router = express.Router();
let tasks = [];
let nextId = 1;
router.get("/", (req, res) => res.json(tasks));
router.post("/", (req, res) => {
const task = { id: nextId++, title: req.body.title, done: false };
tasks.push(task);
res.status(201).json(task);
});
router.patch("/:id", (req, res) => {
const task = tasks.find(t => t.id === Number(req.params.id));
if (!task) return res.status(404).json({ error: "Not found" });
Object.assign(task, req.body);
res.json(task);
});
router.delete("/:id", (req, res) => {
tasks = tasks.filter(t => t.id !== Number(req.params.id));
res.sendStatus(204);
});
module.exports = router;
Track request start timestamp and measure duration on response finish event.
function logger(req, res, next) {
const start = Date.now();
res.on("finish", () => {
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} - ${Date.now() - start}ms`);
});
next();
}
app.use(logger);
Define Mongoose Schema specifying type constraints, required messages, enum allowed values, and defaults.
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: { type: String, required: [true, "Name is needed"], trim: true },
price: { type: Number, min: 0, required: true },
category: { type: String, enum: ["books", "tech", "toys"] },
createdAt: { type: Date, default: Date.now },
});
module.exports = mongoose.model("Product", productSchema);
Establish async connection using mongoose.connect() with environment variable MONGO_URI.
const mongoose = require("mongoose");
async function connectDB() {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("Database connected");
} catch (err) {
console.error("Connection failed:", err.message);
process.exit(1);
}
}
module.exports = connectDB;
Check existing email, hash password using bcrypt.hash(password, 10), and create user record.
const bcrypt = require("bcryptjs");
const User = require("../models/User");
exports.register = async (req, res) => {
const { email, password } = req.body;
if (await User.findOne({ email })) {
return res.status(400).json({ error: "Email already used" });
}
const hash = await bcrypt.hash(password, 10);
const user = await User.create({ email, password: hash });
res.status(201).json({ id: user._id, email: user.email });
};
Compare bcrypt password hashes and sign JWT token using jsonwebtoken library.
const jwt = require("jsonwebtoken");
exports.login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ error: "Invalid credentials" });
}
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1d" });
res.json({ token });
};
Extract Bearer token from authorization header and verify signature using jwt.verify().
function requireAuth(req, res, next) {
const header = req.headers.authorization || "";
const token = header.startsWith("Bearer ") ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: "No token" });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: "Token invalid or expired" });
}
}
Define 4-parameter Express error handling middleware app.use((err, req, res, next) => ...).
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: err.message || "Something went wrong",
});
});
Calculate skip((page-1)*limit) and limit(limit) using Promise.all() for concurrent items and total count query.
router.get("/", async (req, res) => {
const page = Math.max(Number(req.query.page) || 1, 1);
const limit = Math.min(Number(req.query.limit) || 10, 50);
const [items, total] = await Promise.all([
Product.find().sort({ createdAt: -1 }).skip((page - 1) * limit).limit(limit),
Product.countDocuments(),
]);
res.json({ items, page, pages: Math.ceil(total / limit) });
});
Higher-order function wrapping async route handlers with Promise.resolve().catch(next).
const catchAsync = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
router.get("/:id", catchAsync(async (req, res) => {
const product = await Product.findById(req.params.id);
if (!product) return res.status(404).json({ error: "Not found" });
res.json(product);
}));
Use MongoDB $match, $group, and $sort aggregation pipeline stages.
const report = await Order.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$category", revenue: { $sum: "$amount" }, orders: { $sum: 1 } } },
{ $sort: { revenue: -1 } },
]);
Use Mongoose populate() method to auto-fill referenced User document fields.
const postSchema = new mongoose.Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});
const Post = mongoose.model("Post", postSchema);
const posts = await Post.find().populate("author", "name email");
Manage state using useState hook with increment and reset handlers.
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Clicked {count} times</p>
<button onClick={() => setCount(c => c + 1)}>Add</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
Use useEffect hook with fetch API, managing loading, error, and data states.
import { useEffect, useState } from "react";
export default function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
fetch("/api/users")
.then(res => {
if (!res.ok) throw new Error("Request failed");
return res.json();
})
.then(setUsers)
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error}</p>;
return <ul>{users.map(u => <li key={u._id}>{u.name}</li>)}</ul>;
}
Bind form input values to React component state and handle form submission.
import { useState } from "react";
export default function LoginForm({ onSubmit }) {
const [form, setForm] = useState({ email: "", password: "" });
const handleChange = (e) =>
setForm({ ...form, [e.target.name]: e.target.value });
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(form);
};
return (
<form onSubmit={handleSubmit}>
<input name="email" value={form.email} onChange={handleChange} />
<input name="password" type="password" value={form.password} onChange={handleChange} />
<button type="submit">Log in</button>
</form>
);
}
Create custom hook synchronizing React state with browser localStorage.
import { useState, useEffect } from "react";
export function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Use setTimeout inside useEffect with cleanup function to delay value updates.
import { useState, useEffect } from "react";
export function useDebounce(value, delay = 400) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
Check array length before rendering list elements and render fallback message.
export default function TodoList({ todos }) {
if (todos.length === 0) return <p>Nothing to do. Enjoy your day!</p>;
return (
<ul>
{todos.map(t => (
<li key={t.id} style={{ textDecoration: t.done ? "line-through" : "none" }}>
{t.title}
</li>
))}
</ul>
);
}
Configure client-side routing using BrowserRouter, Routes, Route, and Link components.
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
export default function App() {
return (
<BrowserRouter>
<nav><Link to="/">Home</Link> | <Link to="/about">About</Link></nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/products/:id" element={<ProductDetail />} />
<Route path="*" element={<p>Page not found</p>} />
</Routes>
</BrowserRouter>
);
}
Create ThemeContext, Provider component, and custom useTheme hook.
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [dark, setDark] = useState(false);
return (
<ThemeContext.Provider value={{ dark, toggle: () => setDark(d => !d) }}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);
Handle complex cart state transitions (add, remove, clear) using useReducer hook.
import { useReducer } from "react";
function cartReducer(state, action) {
switch (action.type) {
case "add":
return [...state, { ...action.item, qty: 1 }];
case "remove":
return state.filter(i => i.id !== action.id);
case "clear":
return [];
default:
return state;
}
}
export default function Cart() {
const [cart, dispatch] = useReducer(cartReducer, []);
return (
<button onClick={() => dispatch({ type: "add", item: { id: 1, name: "Pen" } })}>
Items: {cart.length}
</button>
);
}
Use axios.create() and request interceptors to automatically append JWT Authorization header.
import axios from "axios";
const api = axios.create({ baseURL: "http://localhost:5000/api" });
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
export default api;
Check token existence and render children or redirect to login via <Navigate />.
import { Navigate } from "react-router-dom";
export default function ProtectedRoute({ children }) {
const token = localStorage.getItem("token");
return token ? children : <Navigate to="/login" replace />;
}
Memoize array filtering using useMemo hook to avoid recalculating on unrelated renders.
import { useMemo, useState } from "react";
export default function ProductSearch({ products }) {
const [term, setTerm] = useState("");
const visible = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(term.toLowerCase())),
[products, term]
);
return (
<>
<input value={term} onChange={e => setTerm(e.target.value)} placeholder="Search..." />
<ul>{visible.map(p => <li key={p.id}>{p.name}</li>)}</ul>
</>
);
}
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.