Express.js Interview Questions
Prepare for your Node.js interviews with the most asked Express.js interview questions and answers for experienced developers. Covers middleware, routing, error handling, performance, and real-world scenarios. Perfect for 2+ to 5+ years experience.
- Express.js kya hai aur Node.js se kaise different hai?
- Express me middleware kya hota hai? Types batao?
- Application-level vs Router-level middleware me difference?
- req, res, next kya hote hain?
- Express.Js me routing kaise kaam karti hai?
- REST API kya hoti hai? Express me kaise banate hain?
- Static files serve kaise karte hain Express me?
- app.use() aur app.get() me difference?
- Error handling middleware kaise likhte hain?
- Async errors ko handle kaise karte ho?
- Express me request validation kaise karte ho?
- Body-parser kya hai? Ab kyun use nahi karte?
- CORS kya hai? Express me kaise handle karte ho?
- JWT authentication Express me kaise implement karte ho?
- Sessions vs Tokens (JWT) difference?
- Rate limiting kaise implement karte ho?
- Multer kya hota hai.?
- Express app ko scalable kaise banate ho?
- Node.js me clustering kya hota hai? Kya aapne ise use kiya hai? Kaise implement kiya?
- Load balancing kaise karte ho?
- Microservices architecture me Express ka role?
- API versioning kaise implement karte ho?
- Security best practices kya follow karte ho?
- Helmet kya karta hai?
- SQL injection aur XSS se kaise bachoge?
- Performance optimize kaise karte ho Express app ka?
- Agar API slow ho rahi hai to kaise debug karoge?
- High traffic handle kaise karoge?
- Agar production me server crash ho raha hai to aap root cause kaise identify karoge?
- Production me logging aur monitoring ka setup kaise karte ho?
- Database connection pooling ko kaise manage karte ho Node/Express app me?
- API me timeout aur retry mechanism kaise implement karte ho?
- Express app me large payloads (big data / file uploads) ko kaise handle karte ho?
- Express me synchronous aur asynchronous middleware me kya difference hai? Real-world example ke sath explain karo.
- Node.js/Express app me memory leak kaise detect aur analyze karte ho? Real-world example ke sath explain karo.
Express.js kya hai aur Node.js se kaise different hai?
Express.js kya hai?
Express.js ek lightweight web framework hai jo Node.js ke upar built hota hai. Iska use APIs aur web applications banane ke liye hota hai. Ye routing, middleware, request/response handling ko easy bana deta hai.
Node.js se difference:
- Node.js:
- Ek runtime environment hai
- JavaScript ko server-side run karne deta hai
- Express.js:
- Ek framework/library hai
- Node.js ke upar kaam karta hai
- Development fast aur structured bana deta hai
Short Answer (2 Line me)-
Node.js ek runtime hai jisme hum JavaScript server par run karte hain, jabki Express.js ek framework hai jo Node.js par APIs aur web apps banana easy aur scalable bana deta hai.
Express me middleware kya hota hai? Types batao?
Express me middleware basically ek function hota hai jo request aur response ke beech me chalta hai. Jab bhi client request bhejta hai, wo direct route par nahi jaati — pehle middleware se pass hoti hai. Middleware ka kaam hota hai request ko process karna (jaise auth check, logging, data parse karna) aur phir next() call karke aage bhejna.
Types of middleware:
- Application-level middleware
Ye poore app par apply hota hai usingapp.use()
→ Jaise logging ya authentication - Router-level middleware
Specific routes ya router ke liye use hota hai
→ Jab tum modular routes bana rahe ho - Built-in middleware
Express ke andar already milte hain
→ Jaiseexpress.json(),express.urlencoded() - Third-party middleware
External packages use karke
→ Jaisecors,morgan - Error-handling middleware
Errors handle karne ke liye
→ Iska syntax thoda alag hota hai(err, req, res, next)
Short Answer -
Middleware wo function hota hai jo request-response cycle ke beech me execute hota hai aur request ko process karke next handler ko forward karta hai.
Application-level vs Router-level middleware me difference?
Application-level middleware poore app par apply hota hai (app.use()), matlab har request par chalega.
Router-level middleware specific routes ya router par apply hota hai (router.use()), matlab sirf selected routes par chalega.
req, res, next kya hote hain?
- req (request): client se aane wali saari info hoti hai (params, body, headers)
- res (response): server se client ko kya bhejna hai (data, status)
- next: ek function hai jo next middleware ya route handler ko call karta hai
Express.Js me routing kaise kaam karti hai?
Express me routing ka matlab hota hai URL aur HTTP method ke basis par request ko handle karna.
Hum app.get(), app.post(), app.put(), app.delete() jaise methods use karke define karte hain ki kaunsi request par kya response dena hai. Jab request aati hai, Express usko match karta hai aur corresponding route handler execute karta hai.
REST API kya hoti hai? Express me kaise banate hain?
REST API ek aisi API hoti hai jo HTTP methods (GET, POST, PUT, DELETE) ka use karke resources ko manage karti hai, aur mostly data JSON format me exchange hota hai.
Express me kaise banate hain?
Express me hum routes define karke API banate hain, jaise app.get(), app.post() etc., aur har route me request handle karke response bhejte hain.
Static files serve kaise karte hain Express me?
Express me static files serve karne ke liye hum express.static() middleware use karte hain.
Isme hum ek folder define kar dete hain (jaise public), aur uske andar ke HTML, CSS, images directly browser se access ho jate hain.
app.use() aur app.get() me difference?
- app.use():
Ye middleware ke liye use hota hai aur sabhi HTTP methods (GET, POST, etc.) par chalega. Mostly common logic (auth, logging) ke liye use hota hai. - app.get():
Ye specifically GET request handle karne ke liye use hota hai aur ek particular route par kaam karta hai.
Error handling middleware kaise likhte hain?
Express me error handling middleware ka syntax thoda alag hota hai — isme 4 parameters hote hain: (err, req, res, next).
app.use((err, req, res, next) => {
res.status(500).json({
message: err.message
});
});
Async errors ko handle kaise karte ho?
Async errors handle karne ke liye hum try-catch use karte hain ya error ko next(err) ke through error middleware tak bhejte hain.
Better approach ye hota hai ki async routes ko ek wrapper function me wrap karein, taki automatically errors handle ho jayein.
Express me request validation kaise karte ho?
Express me request validation ke liye hum middleware use karte hain, jahan request body, params ya query ko validate kiya jata hai.
Usually hum libraries jaise express-validator ya Joi use karte hain taaki input correct format me ho aur invalid data ko reject kiya ja sake.
Body-parser kya hai? Ab kyun use nahi karte?
Body-parser ek middleware tha jo request body (JSON, form data) ko parse karke req.body me available kar deta tha.
Ab Express ke latest versions me ye functionality built-in aa gayi hai (express.json(), express.urlencoded()), isliye alag se body-parser install karne ki zarurat nahi hoti.
CORS kya hai? Express me kaise handle karte ho?
CORS (Cross-Origin Resource Sharing) ek security mechanism hai jo decide karta hai ki ek domain se dusre domain par request allow hogi ya nahi.
Express me hum cors middleware use karte hain aur allowed origins define kar dete hain.
Short Ans :
CORS ek security feature hai jo cross-origin requests ko control karta hai, aur Express me ise cors middleware se handle kiya jata hai.
JWT authentication Express me kaise implement karte ho?
JWT authentication me hum user ko login par ek token generate karke dete hain, aur baad me har request me us token ko verify karke access dete hain.
Express me pehle login route me jsonwebtoken se token generate karte hain, fir ek middleware banate hain jo request ke headers se token verify karta hai aur valid hone par next() call karta hai.
Sessions vs Tokens (JWT) difference?
- Sessions:
Server-side store hote hain, user data server me save hota hai aur client sirf session ID bhejta hai. - JWT (Tokens):
Stateless hote hain, poora data token me encoded hota hai aur client har request me token bhejta hai.
Short interview line:
Sessions server-side stateful hote hain, jabki JWT stateless hota hai jisme user data token me hi store hota hai.
Rate limiting kaise implement karte ho?
Rate limiting implement karne ke liye hum middleware use karte hain jo ek specific time me request count limit karta hai.
Express me commonly express-rate-limit library use karte hain jisme max requests aur time window define kar dete hain.
interview me asie Ans de:
Rate limiting middleware ke through implement hota hai, jahan hum ek time window me max requests limit karke API ko abuse hone se bachate hain.
Multer kya hota hai.?
Multer ek middleware hai jo Express me file uploads handle karne ke liye use hota hai, jaise images ya documents ko server par upload karna.
Ye multipart/form-data ko parse karta hai aur files ko disk ya memory me store kar deta hai.
Express app ko scalable kaise banate ho?
Express app ko scalable banane ke liye hum code ko modular structure (MVC) me likhte hain, heavy tasks ko async/background jobs me daalte hain, aur caching (Redis) use karte hain.
Production me hum load balancer + clustering (PM2) use karte hain aur database optimization (indexes, pooling) karte hain.
Node.js me clustering kya hota hai? Kya aapne ise use kiya hai? Kaise implement kiya?
Clustering Node.js me ek technique hai jisme hum multiple CPU cores ka use karke multiple instances (workers) run karte hain, taaki application parallel requests handle kar sake aur performance improve ho.
Haan, maine clustering use kiya hai — mainly PM2 ke through. PM2 me cluster mode enable karke app ke multiple instances run karte hain, jo load ko automatically distribute karta hai.
pm2 start app.js -i max
Isse jitne CPU cores hain utne instances run ho jate hain.
Load balancing kaise karte ho?
Load balancing ka matlab hota hai incoming requests ko multiple servers/instances me distribute karna, taaki load evenly divide ho aur performance better rahe.
Practical me hum Nginx ya AWS Load Balancer use karte hain jo requests ko different instances (Node.js/Express apps) me forward karta hai.
Microservices architecture me Express ka role?
Express ka use microservices me lightweight HTTP server/framework ke roop me hota hai jisse hum independent services (APIs) build karte hain. Har service ek specific responsibility handle karti hai (jaise user service, order service, payment service) aur Express unke endpoints expose karta hai.
Express ki help se hum:
- REST APIs create karte hain jo dusre services se communicate kar sake
- Middleware use karke auth, logging, validation handle karte hain
- Fast aur lightweight services bana sakte hain jo easily scale ho jati hain
Real-world me services aapas me HTTP APIs ya message queues (RabbitMQ, Kafka) ke through communicate karti hain, aur Express un APIs ko efficiently handle karta hai.
API versioning kaise implement karte ho?
API versioning implement karne ke liye hum URL me version add karte hain, jaise /api/v1/users, /api/v2/users.
Express me hum alag-alag routers bana ke versions handle karte hain, taki naye changes purane clients ko break na karein.
Real-world example:
Maan lo ek e-commerce app hai — pehle /api/v1/orders me basic order data aata tha. Baad me requirement aayi ki order me tracking details aur delivery ETA bhi add karna hai, to humne /api/v2/orders bana diya.
Isse purane mobile apps jo v1 use kar rahe hain wo break nahi hote, aur naye clients v2 use kar sakte hain.
Security best practices kya follow karte ho?
Express app me security ke liye main kuch important best practices follow karta hoon:
- Helmet use karta hoon for secure HTTP headers
- CORS properly configure karta hoon (restricted origins)
- Input validation & sanitization (Joi / express-validator)
- Authentication & authorization (JWT, role-based access)
- Rate limiting to prevent brute-force attacks
- Sensitive data ko .env me store karta hoon (no hardcoding)
- HTTPS enforce karta hoon for secure communication
Short Answer:
Security ke liye helmet, CORS, validation, JWT auth, rate limiting aur HTTPS jaise best practices follow karta hoon taaki app secure rahe.
Helmet kya karta hai?
Helmet Express ka middleware hai jo app ko secure banane ke liye HTTP headers set karta hai.
Ye common attacks jaise XSS, clickjacking, MIME sniffing se protection deta hai.
SQL injection aur XSS se kaise bachoge?
SQL Injection:
User input ko directly query me use nahi karte, balki parameterized queries / ORM (Sequelize, etc.) use karte hain aur input validation karte hain.
XSS:
User input ko sanitize/escape karte hain aur response me unsafe HTML render nahi karte, saath hi Helmet jaise tools use karte hain.
Performance optimize kaise karte ho Express app ka?
Express app ka performance optimize karne ke liye main:
- Caching use karta hoon (Redis) taaki repeated requests fast serve ho
- Database optimization (indexes, optimized queries, connection pooling)
- Compression middleware (response size kam karne ke liye)
- Clustering (PM2) se multi-core usage
- Async/non-blocking code use karta hoon (blocking operations avoid)
- Rate limiting & load balancing for stability
Agar API slow ho rahi hai to kaise debug karoge?
Agar API slow ho rahi hai to main step-by-step debug karta hoon:
- Logs check karta hoon (response time, errors)
- Slow queries identify karta hoon (DB profiling, EXPLAIN)
- Middleware/logic bottleneck check karta hoon
- External API calls ka time check karta hoon
- Load testing / monitoring tools (PM2, New Relic) use karta hoon
High traffic handle kaise karoge?
High traffic handle karne ke liye main:
- Load balancing use karta hoon (Nginx / AWS ELB)
- Clustering (PM2) se multiple instances run karta hoon
- Caching (Redis) use karta hoon taaki DB load kam ho
- Database optimize karta hoon (indexes, pooling)
- Async/background jobs (queues like RabbitMQ) use karta hoon
- Rate limiting apply karta hoon
Short Answer :
High traffic handle karne ke liye load balancing, clustering, caching aur async processing use karke system ko scalable banaya jata hai.
Agar production me server crash ho raha hai to aap root cause kaise identify karoge?
Sabse pehle main logs check karta hoon — PM2 logs, application logs aur system logs (jaise /var/log) — taaki exact error message aur stack trace mil sake.
Uske baad main crash pattern analyze karta hoon — kya ye specific API hit par ho raha hai, ya high traffic par. Agar memory related issue lagta hai to main memory usage aur CPU spikes monitor karta hoon (top, htop, PM2 metrics) taaki memory leak ya infinite loop identify ho sake.
Phir main recent deployments ya code changes review karta hoon, kyunki zyadatar crashes kisi recent change ki wajah se hote hain. Saath hi main unhandled exceptions aur promise rejections check karta hoon, kyunki Node.js me agar ye handle na ho to process crash ho sakta hai.
Agar DB ya external service involved hai to main slow queries ya timeout issues bhi check karta hoon. Zarurat pade to main replicate karne ki koshish karta hoon staging ya local me, taaki exact scenario samajh aaye.
End me, fix apply karne ke baad main monitoring tools (PM2, New Relic, CloudWatch) lagata hoon taaki future me issue proactively detect ho sake.
Production me logging aur monitoring ka setup kaise karte ho?
Production me main logging ke liye structured logging use karta hoon (jaise Winston ya Pino), jisme logs ko proper format (JSON) me store karte hain aur alag-alag levels (info, error, debug) maintain karte hain.
Logs ko centralize karne ke liye unhe ELK stack (Elasticsearch, Logstash, Kibana) ya cloud services (AWS CloudWatch) me bhejte hain, jisse easily search aur analyze ho sake.
Monitoring ke liye main PM2, New Relic ya Datadog use karta hoon jisse CPU, memory, response time aur error rate track hota hai, aur alerts setup karte hain taaki issue aate hi notify ho jaye.
Database connection pooling ko kaise manage karte ho Node/Express app me?
Connection pooling me hum multiple reusable DB connections ka pool create karte hain taaki har request par naya connection create na karna pade, isse performance improve hoti hai.
Express me main ORM ya drivers (jaise Sequelize / MySQL driver) ke through pool size, max/min connections aur timeout configure karta hoon. Har request pool se connection leta hai aur kaam ke baad release kar deta hai.
Saath hi main ensure karta hoon ki connections properly close/release ho, warna connection leak ho sakta hai aur app slow ya crash ho sakta hai.
API me timeout aur retry mechanism kaise implement karte ho?
Timeout implement karne ke liye main HTTP client (jaise Axios) me timeout set karta hoon, taki agar API fixed time me response na de to request fail ho jaye.
Retry ke liye main retry logic lagata hoon — ya to manually (loop/recursive) ya libraries (axios-retry) se — jisme limited attempts aur delay (exponential backoff) set karta hoon, taki system overload na ho.
Production me main ensure karta hoon ki retry sirf safe operations (GET) par ho aur proper logging ho.
Short Answer :
Timeout ke liye request time limit set karte hain aur retry ke liye limited attempts with delay (exponential backoff) use karte hain.
Express app me large payloads (big data / file uploads) ko kaise handle karte ho?
Large payload handle karne ke liye main streaming approach use karta hoon, taki data chunk-wise process ho aur memory overload na ho.
File uploads ke case me main Multer ya direct streams (S3 upload) use karta hoon, aur unnecessary large body ko block karne ke liye request size limit set karta hoon (limit in body parser).
Saath hi main compression enable karta hoon aur agar possible ho to large data ko pagination ya chunking me break kar deta hoon.
Express me synchronous aur asynchronous middleware me kya difference hai? Real-world example ke sath explain karo.
Express me middleware do type ke hote hain — synchronous aur asynchronous — aur inka main difference execution aur handling ka hota hai.
Synchronous middleware:
Ye immediately execute hota hai aur blocking nature ka hota hai. Isme koi async operation nahi hota, aur ye direct next() call karke aage badh jata hai.
Example: logging middleware
app.use((req, res, next) => {
console.log(req.url);
next();
});
Asynchronous middleware:
Isme async operations hote hain jaise DB call, API call, file read, etc. Ye non-blocking hota hai aur jab async task complete hota hai tab next() call hota hai.
Example: user authentication (DB se check)
app.use(async (req, res, next) => {
const user = await User.findById(req.headers.id);
if (!user) return res.status(401).send("Unauthorized");
next();
});
Real-world example:
Maan lo ek e-commerce app hai:
- Synchronous middleware: har request ka log print karna
- Asynchronous middleware: user authentication ya order fetch karna DB se
Key diff:
Synchronous middleware turant execute hota hai, jabki asynchronous middleware me async tasks complete hone ke baad execution aage badhta hai.
Node.js/Express app me memory leak kaise detect aur analyze karte ho? Real-world example ke sath explain karo.
Memory leak tab hota hai jab app memory allocate karta rehta hai lekin properly release nahi karta, jisse time ke saath memory continuously badhti rehti hai aur eventually app crash ho sakta hai.
Detect karne ke liye sabse pehle main memory usage monitor karta hoon — jaise process.memoryUsage(), PM2 metrics, ya tools like New Relic. Agar memory continuously increase ho rahi hai bina drop hue, to ye leak ka sign hai.
Uske baad main heap snapshots aur profiling tools use karta hoon (Chrome DevTools / Node inspector) taaki pata chale kaunse objects memory me stuck hain. Isse exact source identify karna easy ho jata hai.
Phir main code review karta hoon aur common issues check karta hoon:
- Global variables ya caches jo clear nahi ho rahe
- Event listeners jo remove nahi ho rahe
- Unclosed DB connections ya file handles
- Large objects jo memory me hold ho rahe hain
Real-world Example:
Ek project me maine dekha ki API hit hone par memory dheere-dheere badh rahi thi. Investigation me pata chala ki humne ek in-memory cache banaya tha (object me data store kar rahe the) lekin uska cleanup ya TTL nahi tha. Har request me data add ho raha tha aur kabhi remove nahi ho raha tha.
Fix me maine Redis with TTL use kiya aur unnecessary data cleanup implement kiya, jisse memory stable ho gayi.