1. MongoDB Fundamentals
What is MongoDB and its key features?
What is MongoDB and its key features?
Explain BSON vs JSON
Explain BSON vs JSON
What are collections and documents?
What are collections and documents?
Explain CRUD operations
Explain CRUD operations
insertOne(), insertMany(). Read: find(), findOne(). Update: updateOne(), updateMany(), replaceOne(). Delete: deleteOne(), deleteMany(). These operations form the foundation of MongoDB interactions.What is the _id field?
What is the _id field?
_id field is the primary key in MongoDB documents, automatically generated as ObjectId if not provided. It’s unique within a collection and indexed by default for fast lookups.2. MongoDB Advanced Concepts
What is indexing?
What is indexing?
Explain aggregation framework
Explain aggregation framework
$match, $group, $project, $sort, $lookup. It enables complex data transformations and analytics directly in the database.What is sharding?
What is sharding?
Explain replica sets
Explain replica sets
What are embedded vs referenced relationships?
What are embedded vs referenced relationships?
3. Express.js Basics and Middleware
What is Express.js?
What is Express.js?
Explain middleware
Explain middleware
req, res, and next. They execute code, modify req/res, end cycles, or call next(). Types include application-level, router-level, error-handling, and third-party.How does routing work?
How does routing work?
app.METHOD(PATH, HANDLER) syntax for route definition.What are route parameters?
What are route parameters?
/users/:id) accessible via req.params. Query strings (?key=value) are accessed via req.query for optional parameters.How to handle POST requests?
How to handle POST requests?
express.json() and express.urlencoded() middleware to parse request bodies. Access parsed data via req.body in route handlers.What is Express.js and why is it used?
What is Express.js and why is it used?
Example:
Why:
Because Node’s native HTTP module is low-level. Express provides convenient abstractions like routing, middleware, and request parsing.When:
Use it when building REST APIs, microservices, or web apps that require request handling.Where:
It’s the most common framework in production Node.js environments.Explain the middleware concept in Express.js
Explain the middleware concept in Express.js
Example:
Why:
Middleware provides a way to modularize logic — logging, authentication, validation — without polluting route handlers.When:
Use middleware whenever you want to perform an action before reaching your route (or after response, like error logging).Where:
Common examples:express.json()for parsing JSONcors()for handling cross-origin requests- Custom middleware for auth/validation
What types of middleware exist in Express.js?
What types of middleware exist in Express.js?
| Type | Description | Example |
|---|---|---|
| Application-level | Bound to app | app.use() |
| Router-level | Bound to an Express router | router.use() |
| Built-in | Provided by Express | express.json(), express.static() |
| Third-party | Installed via npm | cors, helmet, morgan |
| Error-handling | 4 parameters (err, req, res, next) | Custom error middleware |
Example:
Why:
To create reusable, layered logic pipelines.When:
Whenever you need pre/post-processing around route handlers.Where:
Throughout the Express lifecycle (before/after routes).What is the role of next() in middleware?
What is the role of next() in middleware?
next() passes control to the next middleware in the stack. If not called, the request hangs (no response sent).Example:
Why:
To chain multiple middlewares for modular logic.When:
When you need layered control (logging → validation → controller).Where:
Always in custom middleware unless it ends the request.What's the difference between app.use() and app.get()?
What's the difference between app.use() and app.get()?
| Function | Purpose |
|---|---|
| app.use() | Registers middleware (runs for all methods unless filtered by path) |
| app.get() | Defines a route handler specifically for GET requests |
Example:
Why:
use() is for pre-processing, get() is for request handling.When:
Useuse() for shared logic like authentication.Where:
Across all routes or specific prefixes.How does Express handle the request-response lifecycle?
How does Express handle the request-response lifecycle?
- Request enters Express
- Passes through middleware stack
- If matched, route handler executes
- If no match → 404 handler
- If error → error-handling middleware
Example Flow:
Why:
Understanding this helps you debug request flow and performance.When:
When analyzing middleware order or debugging missed routes.Where:
In Express core — it’s what powers routing and middleware sequencing.How do you handle errors globally in Express.js?
How do you handle errors globally in Express.js?
Example:
Why:
Centralized error handling avoids repeating try/catch everywhere.When:
In production APIs, always define a global error middleware.Where:
Place at the bottom of middleware stack (after routes).What's the difference between res.send(), res.json(), and res.end()?
What's the difference between res.send(), res.json(), and res.end()?
| Method | Purpose |
|---|---|
| res.send() | Sends response (auto-detects type) |
| res.json() | Sends JSON response (sets content-type) |
| res.end() | Ends response without data |
Example:
Why:
Each method suits different scenarios (raw text vs structured data).When:
Use:send()→ text or HTMLjson()→ APIsend()→ streams or empty responses
Where:
Controllers or route handlers.How can you secure your Express app?
How can you secure your Express app?
- Use Helmet → sets HTTP headers
- Use Rate-limiter → prevent brute-force
- Use CORS properly
- Use
express.json({ limit })→ prevent payload overflows - Disable x-powered-by header
- Validate all inputs (with Joi/Zod)
Example:
Why:
Express is not secure by default; hardening prevents XSS, CSRF, and DoS attacks.When:
Always in production environments.Where:
At app initialization or middleware level.How can you handle async errors in Express route handlers?
How can you handle async errors in Express route handlers?
- Try/catch inside route, or
- Wrap with async error handler.
Example:
Why:
Express doesn’t automatically catch async errors without.catch().When:
Always for async routes (DB calls, APIs).Where:
Use asyncHandler pattern across all async routes.How does Express handle routing internally?
How does Express handle routing internally?
Example:
Why:
To provide performant routing and predictable middleware flow.When:
When debugging routing conflicts or order issues.Where:
Inside express/lib/router/layer.js and route.js source.4. Express.js Authentication & Authorization
What is the difference between authentication and authorization?
What is the difference between authentication and authorization?
How do you implement JWT authentication in Node.js?
How do you implement JWT authentication in Node.js?
Steps:
- User logs in with credentials
- Server verifies credentials and issues a signed JWT using jsonwebtoken
- Client stores JWT (usually in localStorage or cookie)
- Client sends JWT in
Authorization: Bearer <token>header for protected routes
Example:
Why:
JWT avoids database lookups on every request (unlike sessions).When:
Use JWT for REST APIs and microservices.Where:
Ideal for stateless systems or distributed apps (like mobile + web).When would you prefer sessions over JWT?
When would you prefer sessions over JWT?
- The app is monolithic and server-rendered (like an Express + EJS app)
- You need easy session invalidation (e.g., logout all sessions)
- You store user-specific state in the backend
Example (session-based login):
Why:
Sessions allow you to track user data server-side and revoke tokens instantly.When:
In traditional web apps or dashboards.Where:
Stored in Redis for scalability.How do you protect routes and implement Role-Based Access Control (RBAC)?
How do you protect routes and implement Role-Based Access Control (RBAC)?
What is the difference between RBAC and ABAC?
What is the difference between RBAC and ABAC?
| Concept | RBAC | ABAC |
|---|---|---|
| Full form | Role-Based Access Control | Attribute-Based Access Control |
| Based on | User role | User + Resource attributes |
| Flexibility | Static | Dynamic (context-aware) |
Example (ABAC):
Why:
ABAC allows more granular control.When:
Use ABAC in enterprise apps needing dynamic policies (like file sharing).Where:
Applied at business logic level.How do you securely store passwords in Node.js?
How do you securely store passwords in Node.js?
How would you implement refresh tokens with JWT?
How would you implement refresh tokens with JWT?
How do you handle token revocation (logout) in JWT-based systems?
How do you handle token revocation (logout) in JWT-based systems?
Common strategies:
- Blacklist tokens in Redis
- Rotate refresh tokens (invalidate old ones)
- Use short expiry times for access tokens
Example:
Why:
Prevents reuse of stolen tokens.When:
During logout or detected suspicious activity.Where:
Store in Redis for quick lookup.What are common security vulnerabilities in authentication systems?
What are common security vulnerabilities in authentication systems?
How would you integrate social logins like Google or Facebook?
How would you integrate social logins like Google or Facebook?
5. React Fundamentals & Core Concepts
What is React?
What is React?
Explain JSX
Explain JSX
React.createElement() calls, providing intuitive UI description with JavaScript expressions.What are components?
What are components?
const MyComponent = (props) => {props.text}. They accept props and return React elements.What are props?
What are props?
<Component prop="value" />.What is state?
What is state?
useState hook: const [count, setCount] = useState(0). State updates trigger re-renders. Never mutate state directly.Explain the Virtual DOM and how React uses it to optimize rendering
Explain the Virtual DOM and how React uses it to optimize rendering
- React creates a new virtual DOM tree
- It diffs it with the previous one (using a diffing algorithm)
- It updates only the changed elements in the real DOM — improving performance
Code Example:
Why it matters:
Directly updating the DOM is expensive. The Virtual DOM allows React to minimize those updates efficiently.Difference between Controlled and Uncontrolled Components
Difference between Controlled and Uncontrolled Components
- Controlled Component: React controls the input’s value using state
- Uncontrolled Component: The DOM handles the input’s value directly via ref
Code Example (Controlled):
Code Example (Uncontrolled):
What are React Hooks? Can you explain how useEffect works with dependencies?
What are React Hooks? Can you explain how useEffect works with dependencies?
useEffectallows you to perform side effects (like data fetching, DOM updates, event listeners)- The dependency array controls when the effect runs
Code Example:
Behavior based on dependencies:
[]→ runs once (on mount)[var]→ runs when var changes- no array → runs on every render
What happens if you don't provide a key in a list?
What happens if you don't provide a key in a list?
How does state lifting work and why is it needed?
How does state lifting work and why is it needed?
Explain the difference between props drilling and context API. When would you use each?
Explain the difference between props drilling and context API. When would you use each?
How do you handle component re-renders and optimize performance?
How do you handle component re-renders and optimize performance?
React.memo()→ prevents re-render if props haven’t changeduseMemo()→ memoizes valuesuseCallback()→ memoizes functions- Avoid anonymous functions inside render if possible
Code Example:
Result:
Child won’t re-render unnecessarily because onClick reference stays stable.What are custom hooks and when do you create one?
What are custom hooks and when do you create one?
6. NEXT JS
Explain the difference between the Pages Router and App Router in Next.js
Explain the difference between the Pages Router and App Router in Next.js
| Feature | Pages Router (pages/) | App Router (app/) |
|---|---|---|
| Introduced | Before Next.js 13 | Next.js 13+ |
| Rendering | CSR, SSR, SSG | RSC, SSR, SSG, ISR |
| File-based routing | Yes | Yes (with nested layouts) |
| Data fetching | getServerSideProps, getStaticProps | Async components or fetch directly |
| Layouts | Custom | Built-in persistent layouts |
| Server Components | ❌ | ✅ Default |
| Client Components | ✅ | ✅ (with “use client”) |
Example (App Router):
Example (Pages Router):
What are Server Components and Client Components in Next.js 13+?
What are Server Components and Client Components in Next.js 13+?
-
Server Components (default):
- Run on the server (never in browser)
- Can fetch data directly
- Reduce bundle size and improve performance
-
Client Components:
- Run in the browser
- Must be marked with “use client”
- Can use useState, useEffect, event handlers, etc.
Example:
How does SSR differ from SSG and ISR in Next.js?
How does SSR differ from SSG and ISR in Next.js?
| Mode | Description | When to Use |
|---|---|---|
| SSR (Server-Side Rendering) | Page rendered at every request | Dynamic data that changes often (e.g., dashboard) |
| SSG (Static Site Generation) | Page pre-rendered at build time | Static content (e.g., blog, docs) |
| ISR (Incremental Static Regeneration) | SSG + revalidation after a time interval | Semi-static content (e.g., news feed) |
Example (ISR):
When would you choose SSR vs CSR?
When would you choose SSR vs CSR?
- SSR: When SEO and fast first paint are important
- CSR (Client-Side Rendering): When user-specific or highly interactive data is needed (like dashboards)
Example CSR (client fetch):
How do you handle API routes in Next.js?
How do you handle API routes in Next.js?
Explain middleware and where it runs
Explain middleware and where it runs
- Redirect or rewrite requests
- Check authentication
- Modify headers
Example:
How does generateMetadata work in the App Router?
How does generateMetadata work in the App Router?
generateMetadata() allows dynamic SEO metadata generation per page.Example:
What are Layouts and Parallel Routes in Next.js?
What are Layouts and Parallel Routes in Next.js?
How does Next.js handle Image Optimization?
How does Next.js handle Image Optimization?
<Image> component optimizes images automatically:- Lazy loading
- Responsive resizing
- WebP conversion
Example:
7. React State Management and Advanced Patterns
What is code splitting?
What is code splitting?
React.lazy() for component-level splitting: const LazyComponent = React.lazy(() => import('./Component')).Explain error boundaries
Explain error boundaries
componentDidCatch and getDerivedStateFromError. Display fallback UI instead of crashing.What are portals?
What are portals?
ReactDOM.createPortal(child, container). Useful for modals, tooltips, overlays maintaining React tree relationship.What is React Router?
What is React Router?
<Route path="/" element={<Component />} />. Navigate with Link or useNavigate hook.Explain performance optimization
Explain performance optimization
React.memo, useCallback, useMemo, code splitting, virtualization, lazy loading, avoid inline functions, proper keys, lift state appropriately.What's the difference between Redux, Zustand, and React Query?
What's the difference between Redux, Zustand, and React Query?
| Library | Purpose | Best For |
|---|---|---|
| Redux | Centralized predictable state management (global state) | Large apps needing structured data flow |
| Zustand | Lightweight state management using hooks | Simpler state sharing without boilerplate |
| React Query (TanStack Query) | Server-state management (fetching, caching, syncing) | Handling API data efficiently |
Example: Redux
Example: Zustand
Example: React Query
Summary:
- Redux → predictable, structured, global state
- Zustand → minimal, fast local/global store
- React Query → asynchronous data fetching & caching
How do you handle server and client data synchronization?
How do you handle server and client data synchronization?
- Use React Query or SWR for automatic refetching
- Use mutations and invalidate queries after updates
Example with React Query:
invalidateQueries ensures fresh data after mutation — syncing server + client.Explain how to use useReducer hook
Explain how to use useReducer hook
How would you implement pagination or infinite scrolling efficiently?
How would you implement pagination or infinite scrolling efficiently?
- Use API parameters like
?page=1&limit=10 - Use React Query with
getNextPageParamfor infinite scroll
Example:
What is hydration and what problems can occur during hydration in Next.js?
What is hydration and what problems can occur during hydration in Next.js?
- Hydration = The process where React on the client attaches event handlers to the already rendered HTML from the server
- Hydration mismatch happens when server-rendered HTML differs from client render output
Example (problematic):
Fix:
Common causes of mismatch:
- Conditional rendering differences between server/client
- Using
window,localStorageon the server - Non-deterministic values during SSR
How do you handle loading and error states in data fetching?
How do you handle loading and error states in data fetching?
How can you persist state across pages or reloads?
How can you persist state across pages or reloads?
How do you prefetch data in Next.js App Router?
How do you prefetch data in Next.js App Router?
What are Higher-Order Components (HOCs) and when would you use them?
What are Higher-Order Components (HOCs) and when would you use them?
Example:
What is the Render Props pattern?
What is the Render Props pattern?
Example:
What is Compound Components pattern?
What is Compound Components pattern?
Example:
What is the Provider Pattern?
What is the Provider Pattern?
Example:
What is code-splitting and how do you implement it in React?
What is code-splitting and how do you implement it in React?
React.lazy() and Suspense for this.Example:
How do you structure large React or Next.js projects?
How do you structure large React or Next.js projects?
- Feature-based organization helps scale
- Shared state or UI logic goes to
/contextor/hooks - Pages are lazy-loaded in Next.js automatically
What are error boundaries and how do they work?
What are error boundaries and how do they work?
Example:
Explain the concept of render optimization in React
Explain the concept of render optimization in React
- Use
React.memo()for pure functional components - Use
useCallbackanduseMemoto memoize functions and computed values - Avoid creating new objects/functions in render unnecessarily
Example:
What is the difference between a monolithic and modular frontend architecture?
What is the difference between a monolithic and modular frontend architecture?
| Aspect | Monolithic | Modular (Micro-frontend) |
|---|---|---|
| Structure | All components tightly coupled and deployed together | App divided into independent modules (built & deployed separately) |
| Team Size | Better for small teams | Ideal for large teams, multiple domains |
| Deployment | Single deployment | Independent deployments |
| Tech Stack | Single technology | Tech diversity (React + Vue + Angular) |
When to use Modular:
- Large teams, multiple domains
- Independent deployments
- Tech diversity requirements
How do you manage global state in large apps?
How do you manage global state in large apps?
- Context API for light global state
- Redux Toolkit / Zustand / Jotai for complex or shared logic
- React Query for server state
Example with Zustand:
8. React and Next JS testing
Why is testing important in React apps?
Why is testing important in React apps?
Types of tests:
- Unit tests → Test small pieces (functions, components)
- Integration tests → Verify component interaction
- E2E tests → Test entire user flows (via Playwright / Cypress)
What testing libraries are commonly used in React and Next.js?
What testing libraries are commonly used in React and Next.js?
- Jest → Testing framework (built-in with Next.js)
- React Testing Library (RTL) → DOM interaction & behavior testing
- Playwright / Cypress → End-to-end browser testing
How do you test a simple React component using Jest and RTL?
How do you test a simple React component using Jest and RTL?
How do you mock API calls in tests?
How do you mock API calls in tests?
How do you test Next.js pages or server functions?
How do you test Next.js pages or server functions?
How do you perform snapshot testing in React?
How do you perform snapshot testing in React?
Example:
How do you test components that use React Context?
How do you test components that use React Context?
How do you debug React apps efficiently?
How do you debug React apps efficiently?
- Use React Developer Tools in browser
- Add
console.log()inside hooks or effects - Use VSCode breakpoints
- Use why-did-you-render library to detect unnecessary re-renders
- For Next.js, run
next dev --inspectfor Node debugging
How do you handle test coverage?
How do you handle test coverage?
Key metrics to aim for:
- 80%+ line coverage
- 70%+ branch coverage
What are common issues you debug in Next.js?
What are common issues you debug in Next.js?
| Problem | Possible Cause | Solution |
|---|---|---|
| Hydration Error | Mismatch between SSR and client rendering | Avoid using browser-only APIs during SSR |
| API Route not working | Wrong file structure or method name | Ensure correct /app/api/.../route.js naming |
| 404 after deploy | Static export paths missing | Check dynamic routes and revalidate configs |
| Performance lag | Over-fetching or large bundle | Use lazy loading, memoization, code-splitting |
9. Performance and Optimization React | Next JS
How do you prevent unnecessary re-renders in React?
How do you prevent unnecessary re-renders in React?
- Wrap pure components with
React.memo - Use
useCallbackto memoize event handlers - Use
useMemofor computed values - Split large components
- Keep state as local as possible
Example:
How do you optimize images and assets in Next.js?
How do you optimize images and assets in Next.js?
How do you handle large bundle sizes?
How do you handle large bundle sizes?
- Use dynamic imports:
- Analyze with:
- Move heavy logic to server components (Next.js App Router)
How does React Suspense help performance?
How does React Suspense help performance?
What are server and client components in Next.js 13+?
What are server and client components in Next.js 13+?
- Server Components: Run on the server; ideal for data fetching and heavy logic
- Client Components: Run in the browser; used for interactivity
Example:
How do you cache API responses in Next.js?
How do you cache API responses in Next.js?
- Use
revalidatefor ISR (Incremental Static Regeneration) - Use fetch caching options (
force-cache,no-store,revalidate)
Example:
What are some performance debugging tools?
What are some performance debugging tools?
- React Profiler → Measures render time
- Lighthouse → Measures Core Web Vitals
- Next.js build analyzer → Bundle size breakdown
- Chrome DevTools Performance tab → JS execution time
What are React rendering phases and how to profile them?
What are React rendering phases and how to profile them?
- Render phase → Reconciliation (diffing virtual DOM)
- Commit phase → Apply changes to real DOM
How do you handle performance in lists (1000+ items)?
How do you handle performance in lists (1000+ items)?
What are best practices for Next.js SEO performance?
What are best practices for Next.js SEO performance?
- Use
generateMetadata()in App Router - Lazy load below-the-fold components
- Preload fonts via
next/font - Optimize routes with static rendering when possible
- Use semantic HTML and proper heading structure
- Implement structured data with JSON-LD
- Ensure fast loading times with image optimization
10. Security and Best Practices in React | Next JS
How do you prevent XSS (Cross-Site Scripting) in React?
How do you prevent XSS (Cross-Site Scripting) in React?
dangerouslySetInnerHTML.Safe Practice:
Never insert user input into HTML directly.How do you secure API routes in Next.js?
How do you secure API routes in Next.js?
- Use authentication middleware
- Validate incoming data with Zod or Yup
- Restrict methods (GET, POST, etc.)
- Avoid exposing sensitive env vars to the client
Example:
How do you store secrets securely in Next.js?
How do you store secrets securely in Next.js?
- Use
.env.localfor local secrets - Access via
process.env.SECRET_KEYon server - Never expose private keys using
NEXT_PUBLIC_prefix unless intentional
How do you prevent CSRF attacks?
How do you prevent CSRF attacks?
- Use tokens or double-submit cookies
- For sensitive actions, validate Origin and Referer headers
- Use libraries like NextAuth.js (handles CSRF internally)
- Implement SameSite cookies
Example cookie settings:
How do you handle authentication securely?
How do you handle authentication securely?
- Use HTTP-only cookies for tokens
- Avoid storing JWT in localStorage (can be stolen via XSS)
- Implement proper session management
- Use secure and sameSite flags for cookies
Secure cookie configuration:
What are CSP (Content Security Policies)?
What are CSP (Content Security Policies)?
Example:
How do you handle rate limiting for APIs?
How do you handle rate limiting for APIs?
How do you prevent sensitive data exposure in logs?
How do you prevent sensitive data exposure in logs?
How to handle CORS safely?
How to handle CORS safely?
- Always whitelist origins
- Avoid using
*in production - Use middleware to configure headers
Example:
Access-Control-Allow-Origin: * in production for sensitive endpoints.How to secure Next.js deployment?
How to secure Next.js deployment?
Security Checklist:
- ✅ Use HTTPS
- ✅ Set
NODE_ENV=production - ✅ Use environment variables, not hardcoded secrets
- ✅ Keep dependencies updated (
npm audit) - ✅ Use a WAF (Web Application Firewall) if available
- ✅ Implement proper CORS policies
- ✅ Use security headers (CSP, HSTS, X-Frame-Options)
- ✅ Regular security scanning and penetration testing
- ✅ Monitor for suspicious activities
- ✅ Implement proper error handling (don’t leak stack traces)
How do you protect sensitive environment variables in Next.js?
How do you protect sensitive environment variables in Next.js?
NEXT_PUBLIC_ are exposed to the client. Sensitive keys (like API secrets or DB credentials) must not use NEXT_PUBLIC_ and should only be accessed on the server (API routes, getServerSideProps, or server components).Example:
What are some common security vulnerabilities in React apps and how do you prevent them?
What are some common security vulnerabilities in React apps and how do you prevent them?
1️⃣ XSS (Cross-Site Scripting):
Occurs when malicious scripts are injected into the DOM.✅ Fix:- Avoid
dangerouslySetInnerHTML - Sanitize input using libraries like DOMPurify
2️⃣ CSRF (Cross-Site Request Forgery):
Attackers trick users into making unwanted requests.✅ Fix:- Use anti-CSRF tokens (NextAuth and other libs handle this)
- Validate origin headers in API routes
3️⃣ Data Leakage via Source Code:
Leaking private tokens in frontend code.✅ Fix:- Never expose secrets in
NEXT_PUBLIC_vars - Validate .env usage during CI/CD
4️⃣ Insecure Direct Object Reference (IDOR):
Users access others’ data by manipulating IDs.✅ Fix:- Always verify authorization on the server
- Never trust frontend route params
How do you handle authentication securely in Next.js?
How do you handle authentication securely in Next.js?
Approach 1: Using NextAuth.js
What are HTTP-only cookies and why are they more secure?
What are HTTP-only cookies and why are they more secure?
How do you handle CORS securely?
How do you handle CORS securely?
How do you prevent open redirects in Next.js?
How do you prevent open redirects in Next.js?
How to secure API routes in Next.js?
How to secure API routes in Next.js?
What is CSP (Content Security Policy) and how does it protect your app?
What is CSP (Content Security Policy) and how does it protect your app?
Example:
How do you secure Next.js API endpoints with JWT?
How do you secure Next.js API endpoints with JWT?
How do you secure Next.js Server Actions or Route Handlers?
How do you secure Next.js Server Actions or Route Handlers?
What are some best practices for secure React + Next.js apps?
What are some best practices for secure React + Next.js apps?
| Category | Best Practice |
|---|---|
| 🔐 Authentication | Use JWT or NextAuth with HttpOnly cookies |
| 🔑 Secrets | Store in .env.local, never in client |
| 🧱 XSS | Sanitize HTML, avoid dangerouslySetInnerHTML |
| 🔄 CSRF | Use anti-CSRF tokens or same-site cookies |
| 🧭 Routing | Validate redirect URLs |
| 🧰 Packages | Audit dependencies with npm audit |
| ⚙️ Headers | Set CSP, X-Frame-Options, Strict-Transport-Security |
| 📦 API | Rate limit requests and validate input |
| 📡 HTTPS | Always use SSL in production |
11. Node.js Advanced Topics
What is Node.js?
What is Node.js?
Explain the Node.js Event Loop. How does it handle asynchronous operations?
Explain the Node.js Event Loop. How does it handle asynchronous operations?
Event Loop Phases (TCCPPI)
- Timers – Executes callbacks from
setTimeout()andsetInterval() - Pending Callbacks – Executes I/O callbacks deferred from the previous cycle
- Idle / Prepare – Internal use
- Poll – Retrieves new I/O events; executes their callbacks
- Check – Executes callbacks from
setImmediate() - Close Callbacks – Executes callbacks like
socket.on('close')
Example
Why this order?
process.nextTick()runs before the event loop continues- Timers (
setTimeout) are queued for the Timers phase setImmediate()runs during the Check phase
When to use:
- Use
process.nextTick()for micro-tasks after the current operation - Use
setImmediate()for tasks after I/O events are processed
What is the difference between process.nextTick() and setImmediate()?
What is the difference between process.nextTick() and setImmediate()?
- process.nextTick() executes before the event loop continues — a micro-task
- setImmediate() executes after the current poll phase — a macro-task
Example:
When to use:
- Use
process.nextTick()for quick callbacks that must run before I/O - Use
setImmediate()when you want to yield to I/O first to prevent blocking
Explain how Node.js handles non-blocking I/O
Explain how Node.js handles non-blocking I/O
Example:
Why:
The file read happens asynchronously; Node doesn’t block waiting for it.Where/When:
Used in high-throughput systems — e.g., API gateways, chat apps — where many concurrent requests are served without thread blocking.What are Streams in Node.js?
What are Streams in Node.js?
Types of Streams:
- Readable – e.g.
fs.createReadStream() - Writable – e.g.
fs.createWriteStream() - Duplex – both readable and writable (e.g. TCP socket)
- Transform – modifies data while reading/writing (e.g. zlib compression)
Example:
Why:
- Efficient for large files or live data (video, logs)
- Uses constant memory regardless of file size
Where:
- File uploads/downloads
- Real-time data transfer
- Log streaming
What is the difference between spawn, fork, and exec in Node.js?
What is the difference between spawn, fork, and exec in Node.js?
| Method | Description | Use Case |
|---|---|---|
| spawn | Launches a new process | For long-running or streaming output |
| exec | Launches a process and buffers entire output | For small output commands |
| fork | Special case of spawn that runs a Node.js script with IPC | For creating worker processes |
Example:
Why/When/Where:
- Use spawn for streaming output (e.g., logs)
- Use exec when you need full command output as a string
- Use fork for scaling CPU-bound tasks or worker threads
What are Worker Threads and how do they differ from the Event Loop?
What are Worker Threads and how do they differ from the Event Loop?
Example:
Why:
To offload heavy computations (e.g. image processing, encryption) so they don’t block the main event loop.Where:
In apps with mixed I/O and CPU workloads, like video encoding servers.How do you handle uncaught exceptions and unhandled promise rejections?
How do you handle uncaught exceptions and unhandled promise rejections?
Example:
Why:
Prevents app from crashing unexpectedly and allows logging/restarting.When/Where:
Use this for graceful shutdown and to catch programming mistakes in production.Explain Cluster Mode in Node.js and how it helps in scaling
Explain Cluster Mode in Node.js and how it helps in scaling
Example:
Why:
- Single Node.js process uses only one CPU core
- Cluster mode scales horizontally across all cores
Where:
Used in production APIs — e.g., Express servers, GraphQL APIs — to handle more traffic efficiently.How does Node.js handle memory management?
How does Node.js handle memory management?
Common causes of leaks:
- Global variables
- Unclosed timers or listeners
- Caching large data objects indefinitely
Example Leak:
When/Where:
Monitor memory with tools like:--inspect+ Chrome DevTools- clinic.js, heapdump,
node --trace-gc
What are Buffers in Node.js?
What are Buffers in Node.js?
Example:
Why:
Buffers allow manipulation of binary data efficiently (e.g., file systems, TCP streams).Where:
Used in file operations, network protocols, and binary serialization.What are Modules in Node.js and how are they resolved?
What are Modules in Node.js and how are they resolved?
Example:
Module Resolution Order:
- Core modules (fs, path)
- Local files (./, ../)
- node_modules directory
Why:
Encapsulation of code — prevents global scope pollution.Where:
Used in all Node.js apps; ES Modules preferred for modern codebases.How do you structure a large-scale Node.js application?
How do you structure a large-scale Node.js application?
Common Structure:
Layers Explained:
- Controller: Handles request/response (HTTP logic)
- Service: Business logic
- Model: Database schema and queries
- Middleware: Reusable pre-processing (auth, validation)
- Routes: Maps endpoints to controllers
Why:
- Improves separation of concerns
- Enables unit testing per layer
- Simplifies onboarding and scalability
Where/When:
Used in all enterprise-level Node.js APIs or microservices where team collaboration and modularization are essential.What are some common design patterns used in Node.js?
What are some common design patterns used in Node.js?
Key Patterns:
| Pattern | Description | Example | Use Case |
|---|---|---|---|
| Singleton | Single shared instance | DB connection pool | Database connections |
| Factory | Creates objects dynamically | Model creation | Dynamic service instantiation |
| Observer | Event-driven | EventEmitter | Real-time systems |
| Middleware | Chain of functions | Express middlewares | API requests |
| Repository | Abstract data layer | Repository class | Decoupled DB logic |
| Decorator | Adds behavior without altering | Wrapping services | Logging, caching |
Singleton Pattern Example:
When: Use for connection pools, config objects, caches
Factory Pattern Example:
When: Use for service selection (e.g., multiple gateways, APIs)
What is MVC (Model-View-Controller) and how is it used in Node.js?
What is MVC (Model-View-Controller) and how is it used in Node.js?
- Model: Manages data and database operations
- View: Renders UI (in REST APIs, often JSON)
- Controller: Handles requests, uses Model to get data, and sends responses
Example:
Why:
Encourages separation of concerns, clean testing, and reusability.Where/When:
Common in Express-based web APIs and server-rendered apps.How would you design a scalable microservices architecture in Node.js?
How would you design a scalable microservices architecture in Node.js?
Key Components:
- Each service has own database, own deployment
- Communication via REST, gRPC, or message queues (e.g., RabbitMQ, Kafka)
- Use API Gateway for centralized routing/auth
Example Setup:
Example Communication:
Why:
- Independent scaling and deployment
- Easier fault isolation
- Better for large teams or multi-domain systems
When/Where:
Used in enterprise systems (e.g., eCommerce, SaaS) where modularity and scaling are critical.How do microservices communicate with each other?
How do microservices communicate with each other?
| Type | Example | Use Case |
|---|---|---|
| Synchronous (Request-Response) | REST, gRPC | Real-time data |
| Asynchronous (Event-driven) | RabbitMQ, Kafka, Redis Pub/Sub | Decoupled systems |
Asynchronous Messaging Example (RabbitMQ):
Why:
Async messaging improves resilience and fault tolerance.When/Where:
Use async communication when loose coupling is desired (e.g., sending notifications after order creation).Explain Repository Pattern and why it's useful
Explain Repository Pattern and why it's useful
Example:
Why:
- Makes business logic database-agnostic
- Simplifies unit testing (mock repositories)
- Promotes clean architecture
When/Where:
Used in large teams where database changes should not affect business logic.What is Dependency Injection and how can it be applied in Node.js?
What is Dependency Injection and how can it be applied in Node.js?
Example:
Why:
- Enables loose coupling and easier testing
- Supports inversion of control
When/Where:
Used in testable architectures, e.g., NestJS framework (which has DI built-in).How do you handle configuration management in Node.js across environments?
How do you handle configuration management in Node.js across environments?
Example Structure:
dotenv or config.Example with dotenv:
Why:
- Keeps secrets out of source code
- Easier environment portability
Where/When:
In CI/CD pipelines and multi-environment deployments (e.g., AWS, Docker).What is a layered architecture in backend design?
What is a layered architecture in backend design?
Typical Layers:
- Presentation (Controller) – Handles requests
- Business (Service) – Contains logic
- Data (Repository) – Handles persistence
- Integration (External APIs) – Handles external comms
Example Flow:
Why:
- Makes the system modular, testable, and maintainable
Where:
Used in enterprise backends and API-first architectures.How would you handle versioning in REST APIs?
How would you handle versioning in REST APIs?
Ways to Version:
- URL-based:
/api/v1/users - Header-based:
Accept: application/vnd.api.v2+json - Query-based:
/users?version=2
Example:
Why:
Maintains backward compatibility and smooth client migration.When/Where:
Use when rolling out breaking API changes.Explain how you'd implement CQRS (Command Query Responsibility Segregation)
Explain how you'd implement CQRS (Command Query Responsibility Segregation)
What are modules in Node.js and why are they important?
What are modules in Node.js and why are they important?
Node.js supports three main types of modules:
- Core Modules (built-in) → e.g., fs, path, http
- Local Modules → custom files in your app
- Third-party Modules → installed from npm (e.g., express, lodash)
Example:
Why:
To promote reusability and separation of concerns. Without modules, everything would live in one file, making maintenance and testing hard.When:
Use modules when splitting logic — routes, services, utilities, models, etc.Where:
Common in every medium to large-scale Node.js app, especially with MVC or layered architecture.Explain the difference between CommonJS (require) and ES Modules (import)
Explain the difference between CommonJS (require) and ES Modules (import)
| Feature | CommonJS (require) | ES Modules (import) |
|---|---|---|
| Loading | Synchronous | Asynchronous |
| Syntax | const x = require('x') | import x from 'x' |
| Scope | Wrapped in function | Strict top-level |
| Default in | Node.js before v14 | Modern Node.js (with “type”: “module”) |
Example:
Why:
ESM is the modern standard (tree-shaking, async loading, static analysis).When:
- Use CommonJS in legacy or mixed codebases
- Use ESM for modern projects (especially with TypeScript or Next.js APIs)
Where:
Configured via package.json →"type": "module"What is the difference between MVC and layered architecture in Node.js?
What is the difference between MVC and layered architecture in Node.js?
| Concept | MVC | Layered Architecture |
|---|---|---|
| Pattern | Model–View–Controller | Request–Controller–Service–Repository |
| Purpose | Web apps with UI | APIs and backend systems |
| Focus | Separation of UI and logic | Logical separation by responsibility |
Example Layered Architecture Flow:
Why:
Each layer has a single responsibility — easy to test and change independently.When:
For scalable APIs and microservices.Where:
Used in enterprise Node.js apps (Express, NestJS, Fastify-based systems).How do you manage environment variables in Node.js?
How do you manage environment variables in Node.js?
Example:
Why:
Keeps sensitive data (like DB passwords, API keys) out of code.When:
Always use environment variables for configuration.Where:
process.env→ globally accessible- Used in CI/CD pipelines, Docker, Kubernetes secrets, etc.
What is dependency injection and why is it useful in Node.js architecture?
What is dependency injection and why is it useful in Node.js architecture?
Example:
Why:
- Makes testing easier (can inject mocks)
- Improves flexibility and maintainability
When:
Used heavily in frameworks like NestJS or in test-driven architectures.Where:
Service layers, repositories, utilities, or external integrations.How do you handle circular dependencies in Node.js modules?
How do you handle circular dependencies in Node.js modules?
Example:
Solution:
- Refactor shared logic into a new module
- Use dependency injection
- Lazy-load the dependency inside a function
Why:
To prevent runtime bugs due to incomplete module initialization.When:
When modules reference each other’s exports.Where:
Common in large codebases with intertwined controllers/services.How do you organize routes in an Express application?
How do you organize routes in an Express application?
What are 'config', 'utils', and 'helpers' folders used for?
What are 'config', 'utils', and 'helpers' folders used for?
| Folder | Purpose | Example |
|---|---|---|
| config | Centralized configurations | DB, environment setup |
| utils | Reusable functions | formatters, loggers, date handlers |
| helpers | Request-specific helper logic | validation, response shaping |
Example:
Why:
Encourages DRY (Don’t Repeat Yourself) coding.When:
Used in any mid-size project to centralize repetitive logic.Where:
Globally accessible via imports across layers.How do you separate concerns in a Node.js microservice architecture?
How do you separate concerns in a Node.js microservice architecture?
- Each service owns a single business domain
- Communicates via APIs, queues, or message brokers (e.g., RabbitMQ, Kafka)
- Uses its own database
Example Architecture:
Why:
To achieve scalability, fault isolation, and independent deployment.When:
When the app grows large and needs distributed scaling.Where:
Used in large enterprise systems (e.g., Uber, Netflix architectures).12. Node.js Testing and Debugging
Why is testing important in backend development, and what types of testing do you perform in Node.js projects?
Why is testing important in backend development, and what types of testing do you perform in Node.js projects?
Types of testing in Node.js:
-
Unit Testing – Tests individual functions or modules
- Tools: Jest, Mocha, Chai
- Example: testing a utility function like
calculateTax()
-
Integration Testing – Tests multiple components working together
- Example: testing API endpoints interacting with database and services
-
End-to-End (E2E) Testing – Simulates real user scenarios
- Tools: Supertest, Cypress
- Regression Testing – Ensures new code doesn’t break existing functionality
-
Performance / Load Testing – Evaluates API performance under stress
- Tools: Artillery, K6
Why:
Improves code reliability and confidence in deployment.When:
After each module development or before merging into main branch.Where:
Applied across APIs, database queries, and business logic layers.What is Unit Testing and how do you implement it in Node.js?
What is Unit Testing and how do you implement it in Node.js?
Why:
To verify that each unit of your code performs as intended without depending on external systems.When:
During development or before integration.Example using Jest:
Where:
Stored inside a__tests__ folder or with .test.js extension inside the same module directory.How do you test API endpoints in a Node.js app?
How do you test API endpoints in a Node.js app?
How do you mock external dependencies or services during testing?
How do you mock external dependencies or services during testing?
Why:
To ensure tests run fast, deterministically, and don’t depend on network or environment.When:
When your code calls APIs, databases, or third-party SDKs.Example using Jest Mocks:
Where:
In any module that uses third-party dependencies like AWS SDK, Stripe, or Axios.How do you debug a Node.js application?
How do you debug a Node.js application?
Common methods:
-
Console logging:
Quick and easy but not ideal for large projects.
-
Node Inspector / Chrome DevTools:
Run app with:
Then open
chrome://inspect→ Attach debugger → Add breakpoints. -
VS Code Debugger:
Add a launch.json config:
-
PM2 Logs:
For production debugging:
When:
During development or after reproducing a bug reported from QA.Where:
You can debug application logic, event loops, or async operations.How do you handle errors gracefully in Node.js applications?
How do you handle errors gracefully in Node.js applications?
What are some common debugging tools or libraries used in Node.js?
What are some common debugging tools or libraries used in Node.js?
- Node.js Inspector – built-in debugger for step-through debugging
- Chrome DevTools – UI-based debugging
- VS Code Debugger – integrated IDE tool
- PM2 – process manager for logs and metrics
- Clinic.js – performance profiler
- Winston / Pino – structured logging libraries
Why:
They help in isolating performance bottlenecks, memory leaks, and runtime errors.Where:
Use locally (VS Code/Chrome) or in production (PM2, Winston).How do you ensure test coverage and integrate testing into CI/CD?
How do you ensure test coverage and integrate testing into CI/CD?
Tool: Jest provides built-in coverage reports.
CI/CD Integration (GitHub Actions example):
Why:
Automatically ensures all commits pass tests before merging.When:
Triggered on every pull request or push to main branch.How do you debug a memory leak in Node.js?
How do you debug a memory leak in Node.js?
Detection Steps:
-
Monitor heap usage:
-
Use Chrome DevTools:
- Run
node --inspect - Open Heap Snapshots → Compare over time
- Run
- Use Clinic.js or Memwatch-next
Common causes:
- Global variables
- Unclosed timers
- Unreleased event listeners
Fix:
- Use WeakMap for temporary references
- Remove listeners:
- Close database connections
13. Database Design
How do you decide between SQL and NoSQL for a project?
How do you decide between SQL and NoSQL for a project?
| SQL (Relational) | NoSQL (Document/Key-Value) |
|---|---|
| Structured schema (tables, columns) | Flexible schema (JSON, documents) |
| Strong relationships (JOINs) | Denormalized, nested data |
| ACID transactions | Eventual consistency |
| Example: PostgreSQL, MySQL | Example: MongoDB, DynamoDB |
Example Use Cases:
- SQL: Financial systems, HR platforms (strong relationships)
- NoSQL: E-commerce product catalogs, social feeds (flexible schema)
Why:
SQL enforces strict integrity, NoSQL provides scalability.When:
Choose SQL when data relations are strong; NoSQL for fast-growing, schema-less data.Where:
SQL → transactional layer; NoSQL → analytics or caching layer.Explain normalization and denormalization. When would you use each?
Explain normalization and denormalization. When would you use each?
- Normalization: Process of organizing data to reduce redundancy and improve consistency
- Denormalization: Combining related data into a single structure to improve read performance
Example:
Normalized (two tables):Why:
Normalization improves consistency; denormalization improves read speed.When:
Normalize for frequent writes, denormalize for heavy reads.Where:
E.g., OLTP → normalized; OLAP/NoSQL → denormalized.What is an index? How does it improve performance, and when can it hurt?
What is an index? How does it improve performance, and when can it hurt?
Explain transactions in databases. How are they handled in Node.js?
Explain transactions in databases. How are they handled in Node.js?
Example (PostgreSQL with Sequelize):
Why:
Prevents partial updates when one step fails.When:
Use for multi-table or dependent operations (e.g., payments, inventory).Where:
Implement in service layer functions handling multi-step DB operations.How do you optimize slow database queries?
How do you optimize slow database queries?
- Use
EXPLAINorexplain()to inspect query execution plan - Add proper indexes
- Avoid
SELECT *; specify columns - Paginate large queries
- Cache repetitive queries
Example (MongoDB):
Example (Redis caching):
Why:
Optimized queries save cost and improve API response times.When:
Apply during scaling or under heavy load.Where:
Inside data-access layer (repositories).What are database relationships and how do you handle them in Node.js?
What are database relationships and how do you handle them in Node.js?
- One-to-One: User ↔ Profile
- One-to-Many: User → Orders
- Many-to-Many: Students ↔ Courses
Example (MongoDB - embedding vs referencing):
Why:
Embedding improves read speed; referencing saves space.When:
Embed for frequent reads; reference for frequent writes.Where:
Schema design phase, based on access patterns.How do you handle pagination efficiently?
How do you handle pagination efficiently?
What are database migrations and why are they important?
What are database migrations and why are they important?
Example (with Sequelize):
Example (migration file):
Why:
Ensures consistent schema across environments (dev, staging, prod).When:
Whenever adding/removing/modifying columns or constraints.Where:
Stored in/migrations folder, managed by ORM/CLI.How do you scale databases in high-traffic applications?
How do you scale databases in high-traffic applications?
- Read replicas — offload read traffic
- Sharding — partition data by key (e.g., userId)
- Caching — Redis/Memcached for frequent reads
- Connection pooling — reuse DB connections
Example:
Why:
Prevents bottlenecks under high load.When:
Beyond 10k+ users or concurrent reads.Where:
Database + ORM configuration level.How do you ensure data consistency in distributed systems?
How do you ensure data consistency in distributed systems?
Patterns:
- Two-phase commit (2PC) for strict consistency
- Eventual consistency for scalability
- Sagas pattern for distributed transactions
Example (Sagas):
Why:
Keeps data correct even across microservices.When:
In event-driven or microservice architectures.Where:
Implement at service orchestration level.What are ACID and BASE principles?
What are ACID and BASE principles?
| ACID (SQL) | BASE (NoSQL) |
|---|---|
| Atomicity | Basically Available |
| Consistency | Soft-state |
| Isolation | Eventual consistency |
| Durability |
Why:
ACID ensures reliable transactions; BASE ensures availability at scale.When:
Use ACID for critical systems (banking), BASE for high-volume systems (social media).Where:
Choose based on business priority: consistency vs availability.14. API Design & Best Practices
What are RESTful APIs and their main principles?
What are RESTful APIs and their main principles?
Core Principles:
- Statelessness → Server doesn’t store client state between requests
- Uniform Interface → Consistent structure for all endpoints (
/users,/products) - Client-Server Separation → Independent evolution of frontend & backend
- Cacheable → Responses can be cached for performance
- Layered System → Requests pass through intermediaries like load balancers or proxies
Example:
Why:
REST’s simplicity makes it ideal for large-scale distributed systems.When:
Use for stateless communication (e.g., SaaS apps).Where:
Commonly implemented with Express.js or NestJS.How would you design an API for scalability and maintainability?
How would you design an API for scalability and maintainability?
Use modular folder structure:
- Follow Controller-Service-Repository pattern
- Use async/await and central error handling
- Add pagination, filtering, sorting
Example:
Why:
Separation of concerns ensures scalability and testability.When:
For medium to large projects.Where:
Apply across all route modules for consistency.What's the difference between PUT and PATCH?
What's the difference between PUT and PATCH?
| Method | Purpose | Example |
|---|---|---|
| PUT | Replace the entire resource | { "name": "Ali", "email": "x@x.com" } |
| PATCH | Update part of a resource | { "email": "new@x.com" } |
Example:
Why:
Use PATCH for partial updates to avoid overwriting data.When:
Frontend sends only changed fields.Where:
In APIs supporting user profile updates, etc.How do you handle errors and validation in REST APIs?
How do you handle errors and validation in REST APIs?
How do you handle versioning in APIs?
How do you handle versioning in APIs?
How would you secure an API?
How would you secure an API?
- Authentication & Authorization (JWT, OAuth2)
- Input validation (prevent SQL/NoSQL injection)
- Rate limiting (prevent brute-force)
- CORS control
- HTTPS for encryption
Example (rate limiting):
Why:
Prevents abuse, leaks, and attacks.When:
Always — security should be baked in early.Where:
Applied globally or per route.What are idempotent methods in REST APIs?
What are idempotent methods in REST APIs?
| Method | Idempotent? | Example |
|---|---|---|
| GET | ✅ Yes | Fetching user |
| PUT | ✅ Yes | Updating same data |
| DELETE | ✅ Yes | Deleting same resource again |
| POST | ❌ No | Creates a new record each time |
Example:
Why:
Idempotency ensures reliability in retry scenarios.When:
Especially in payment APIs or distributed systems.Where:
Route and controller logic level.How would you design pagination, filtering, and sorting?
How would you design pagination, filtering, and sorting?
How do you document APIs effectively?
How do you document APIs effectively?
How would you handle rate limiting and throttling?
How would you handle rate limiting and throttling?
What are some common API response codes and their meanings?
What are some common API response codes and their meanings?
| Code | Meaning | Use Case |
|---|---|---|
| 200 | OK | Successful GET |
| 201 | Created | Resource created (POST) |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Validation error |
| 401 | Unauthorized | Missing/invalid token |
| 403 | Forbidden | Access denied |
| 404 | Not Found | Resource doesn’t exist |
| 500 | Internal Server Error | Unexpected error |
Example:
Why:
Clear status codes improve debugging and API usability.When:
Always respond with meaningful HTTP codes.Where:
Controller layer.When would you choose GraphQL over REST?
When would you choose GraphQL over REST?
| REST | GraphQL |
|---|---|
| Multiple endpoints | Single endpoint /graphql |
| Fixed response shape | Client defines response |
| Over-fetching common | Fetch only needed fields |
| Simpler caching | Complex but flexible queries |
Example:
Why:
GraphQL avoids under/over-fetching.When:
For complex UIs needing custom data shapes (like dashboards).Where:
Use Apollo Server or Yoga with Node.js.15. Caching and Performance Optimization
What is caching and why is it important in Node.js applications?
What is caching and why is it important in Node.js applications?
Why:
- Reduces response time
- Minimizes database load
- Improves scalability and user experience
When to use:
When you have repetitive, read-heavy operations such as:- Fetching static product details
- Returning popular posts
- Computing costly aggregations
Where:
Typically used:- Between the API and the database
- At CDN level for static assets
- In-memory (e.g., Redis, Node cache) for API data
Example:
What are different types of caching in Node.js?
What are different types of caching in Node.js?
1. In-memory cache:
- Stored in Node process memory using packages like node-cache or lru-cache
- Fastest but not shared across multiple server instances
- Best for: Single-instance apps, computed results
2. Distributed cache (Redis / Memcached):
- External in-memory databases shared across multiple app instances
- Best for: Scalable and load-balanced applications
3. Browser caching / CDN caching:
- For static files like images, scripts, and CSS
- Best for: Reducing load time for front-end users
4. Application-level caching:
- Using HTTP headers like Cache-Control, ETag, or response-level caching middleware
How do you identify performance bottlenecks in a Node.js app?
How do you identify performance bottlenecks in a Node.js app?
Node’s built-in profiler:
Performance monitoring tools:
- PM2 monitoring dashboard
- New Relic, Datadog, or AppDynamics for production-level insights
Steps to identify bottlenecks:
- Measure response time and CPU usage
- Analyze event loop lag (using clinic.js or node —inspect)
- Check for slow database queries and missing indexes
- Profile memory leaks via heap snapshots
When:
Always perform during load testing before production deployment.How do you optimize a Node.js application for better performance?
How do you optimize a Node.js application for better performance?
1. Use asynchronous code properly:
Avoid blocking the event loop by using non-blocking async operations.2. Enable GZIP compression:
Compress HTTP responses using middleware like compression.3. Use Redis or in-memory cache:
Cache frequent DB queries to reduce load.4. Cluster your Node process:
Utilize multiple CPU cores using cluster or PM2.5. Optimize database queries:
Use proper indexes, projections, and pagination.6. Use streaming for large data:
Instead of loading entire data into memory.7. Use load balancing & reverse proxies (Nginx):
Helps distribute load across multiple Node instances.What is Redis and how do you use it for caching in Node.js?
What is Redis and how do you use it for caching in Node.js?
- Caching responses
- Session storage
- Pub/Sub systems
- Rate limiting
Why Redis:
- Very fast (stores data in RAM)
- Persistent (can save snapshots to disk)
- Supports TTL (time-to-live) expiration
Example:
When:
When your system frequently requests the same data from a slow data source like MongoDB or an external API.What is event loop blocking and how does it impact performance?
What is event loop blocking and how does it impact performance?
How do you handle rate limiting and throttling for performance?
How do you handle rate limiting and throttling for performance?
How do you measure memory usage and detect memory leaks in Node.js?
How do you measure memory usage and detect memory leaks in Node.js?
- Run app with
node --inspect - Open
chrome://inspect - Take Heap Snapshots and compare over time
When leaks occur:
- Global variables not freed
- Large cached data without TTL
- Event listeners not removed
Where to fix:
Ensure proper cleanup using:Conclusion & Interview Tips
This comprehensive guide covers essential MERN Stack interview questions across all four technologies. The MERN stack combines MongoDB, Express.js, React, and Node.js to create powerful full-stack web applications.Key Interview Preparation Tips
- Master fundamentals before advanced topics
- Build full-stack projects for hands-on experience
- Understand how technologies integrate
- Focus on best practices and security
- Practice explaining your thought process
- Review recent updates and ecosystem changes
- Prepare for coding challenges and system design
- Study common architectural patterns
During the Interview
- Ask clarifying questions before coding
- Think aloud to show your problem-solving approach
- Consider edge cases and error handling
- Discuss trade-offs in your solutions
- Be honest about what you don’t know
- Show enthusiasm for learning
Technical Skills to Demonstrate
- Database design and query optimization
- RESTful API development
- Component architecture and state management
- Asynchronous programming patterns
- Security best practices
- Performance optimization techniques
- Testing and debugging strategies
- Deployment and DevOps basics