Top 40 Express.js Interview Questions & Answers
Top 40 Express.js interview questions and answers for Node.js developers: routing, middleware, error handling, REST APIs, JWT auth, security and testing.
Express Basics & Routing
Q1. What is Express.js?
A minimal, unopinionated web framework for Node.js. It adds routing, middleware and helpers for requests and responses on top of Node's http module.
Q2. Why use Express instead of the plain http module?
Express gives routing by method and path, easy JSON parsing, middleware chaining and response helpers like res.json(), which would take a lot of manual code with http alone.
Q3. How do you create a basic Express server?
Create const app = express(), add routes such as app.get('/', (req, res) => res.send('Hi')), and start it with app.listen(3000).
Q4. What is express.Router()?
A mini-app for grouping related routes and middleware, such as all /users routes in one file, which you mount with app.use('/users', router).
Q5. What is the difference between req.params, req.query and req.body?
req.params holds route parameters like :id. req.query holds query string values. req.body holds the parsed request body, which needs body-parsing middleware.
Q6. How do you parse JSON request bodies?
Add app.use(express.json()). For HTML form posts, add app.use(express.urlencoded({ extended: true })).
Q7. What does app.route() do?
It chains handlers for different methods on the same path, as in app.route('/books').get(list).post(create), which avoids repeating the path.
Q8. What is the difference between res.send(), res.json() and res.end()?
res.send() sends a string, buffer or object and sets the content type. res.json() always sends JSON. res.end() ends the response without adding a body.
Q9. How do you serve static files?
Use app.use(express.static('public')), which serves files in that folder by path. Add a prefix with app.use('/static', express.static('public')).
Q10. What changed in Express 5?
Rejected promises in async handlers are now passed to error-handling middleware automatically, path pattern syntax is stricter, and some old methods were removed. It requires Node.js 18 or later.
Middleware
Q11. What is middleware in Express?
A function with (req, res, next) that runs during a request. It can read or change the request and response, end the request, or call next() to pass control on.
Q12. What types of middleware exist?
Application-level with app.use, router-level with router.use, error-handling with four arguments, built-in such as express.json, and third-party such as cors and helmet.
Q13. Why does middleware order matter?
Middleware runs in the order it is added. Body parsing must come before routes that read req.body, and error handlers must come last.
Q14. What happens if middleware does not call next()?
The request stops there. If that middleware also does not send a response, the client hangs until it times out.
Q15. How do you apply middleware to one route only?
Pass it before the handler, as in app.get('/admin', requireAuth, handler). Several middleware functions can be listed in order.
Q16. How do you write logging middleware?
Record the start time, then listen to res.on('finish') to log the method, URL, status and duration, and call next(). Libraries such as morgan or pino-http do this for you.
Q17. What does the cors middleware do?
It adds Cross-Origin Resource Sharing headers so browsers allow requests from other origins. Configure allowed origins explicitly in production instead of *.
Q18. What does next('route') do?
It skips the remaining handlers for the current route and moves to the next matching route. It only works in handlers added with app.METHOD or router.METHOD.
Q19. How do you share data between middleware?
Attach it to req, such as req.user after authentication, or to res.locals for data used when rendering a response.
Q20. What is the difference between app.use() and app.all()?
app.use() matches a path prefix, so /api also matches /api/users. app.all() matches the exact path for every HTTP method.
Error Handling & REST APIs
Q21. How do you write error-handling middleware?
Write a function with four arguments, (err, req, res, next), and add it after all routes. It receives errors passed to next(err) or thrown in handlers.
Q22. How do you handle errors in async route handlers?
In Express 5, rejected promises reach the error handler automatically. In Express 4, wrap handlers in try/catch and call next(err), or use a wrapper such as express-async-errors.
Q23. How do you return a 404 for unknown routes?
Add a middleware after all routes that responds with res.status(404).json({ message: 'Not found' }), since it only runs when nothing else matched.
Q24. How do you design a REST API in Express?
Use nouns for resources, such as /users, HTTP methods for actions, correct status codes, routers per resource, input validation, and a consistent JSON error format.
Q25. How do you validate request input?
Use a library such as Zod, Joi or express-validator in middleware, and return a 400 with the validation errors before the handler runs.
Q26. How do you structure a large Express app?
Split by feature into routes, controllers, services and data access layers. Keep business logic out of route handlers so it can be tested without HTTP.
Q27. How do you implement pagination?
Read page and limit from req.query, apply them to the database query with limit and offset or a cursor, and return the items with total or next-page information.
Q28. How do you upload files in Express?
Use middleware such as multer to parse multipart/form-data. Limit file size and type, and store files in object storage rather than on the server disk.
Q29. What is the difference between res.redirect() and res.render()?
res.redirect() sends a 3xx status telling the browser to request another URL. res.render() renders a view template on the server and sends the HTML.
Q30. How do you version an API in Express?
Mount routers under version prefixes such as app.use('/api/v1', v1Router), so old clients keep working while you change v2.
Security, Performance & Testing
Q31. How do you implement JWT authentication?
On login, sign a token with jsonwebtoken. A middleware reads the Authorization: Bearer header, verifies the token, sets req.user, and rejects invalid tokens with 401.
Q32. How do you secure an Express app?
Use helmet for security headers, validate input, use rate limiting, keep secrets in environment variables, use HTTPS, and keep dependencies up to date with npm audit.
Q33. What does helmet do?
It sets security-related HTTP headers such as Content-Security-Policy, Strict-Transport-Security and X-Content-Type-Options to protect against common attacks.
Q34. How do you add rate limiting?
Use express-rate-limit to cap requests per IP over a time window. With several servers, store counts in Redis so the limit is shared.
Q35. How do you prevent SQL and NoSQL injection?
Use parameterised queries or an ORM, never build queries from raw input, and validate input types, so objects such as { "$gt": "" } are rejected.
Q36. How do you improve Express performance?
Enable gzip or Brotli compression, cache responses, avoid blocking the event loop with heavy synchronous work, use a fast logger, and run several processes with the cluster module or PM2.
Q37. How do you handle environment configuration?
Read settings from process.env, load a .env file in development with dotenv or Node's --env-file flag, and validate required variables at startup.
Q38. How do you test Express routes?
Use supertest with Jest, Vitest or the Node test runner. Pass the app object without starting a server, and assert on status codes and response bodies.
Q39. How do you shut down an Express server gracefully?
On SIGTERM, call server.close() to stop new connections, let in-flight requests finish, close database connections, then exit.
Q40. What is the difference between Express and NestJS?
Express is minimal and leaves structure to you. NestJS builds on Express or Fastify and adds modules, dependency injection, decorators and TypeScript-first conventions for large teams.