Technology

Express.js Interview Questions and Answers

Express.js is the most widely used Node.js web framework. These Express.js interview questions cover routing, request and response objects for freshers, then middleware, error handling, authentication, validation, security, testing and project structure for experienced backend developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise Express.js questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Express.js Interview Questions with answers. Examples: What is Express.js? How do you define routes in Express? What is middleware in Express? How do you handle errors in Express?
Express.js Interview Questions: 30 questions with model answers on this page.

Basic Express.js interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is Express.js?

Answer flow · 3 steps
  1. Express is a minimal, flexible web framework for Node.js that makes it easy to build APIs and web servers.

  2. It provides routing, middleware, helpers for requests and responses, and template engine support, and leaves other choices, such as database and validation libraries, to you.

  3. Its simplicity and huge ecosystem make it the most common Node.js framework.

2. How do you define routes in Express?

With methods matching HTTP verbs: app.get('/users', handler), app.post, app.put, app.patch and app.delete. Route parameters are read from req.params, as in /users/:id, query strings from req.query and the JSON body from req.body after app.use(express.json()). express.Router() groups related routes into modules mounted with app.use('/api/users', router).

3. What is middleware in Express?

Answer flow · 3 steps
  1. Middleware is a function with (req, res, next) that runs during the request-response cycle.

  2. It can read or modify the request, end the response, or call next() to pass control on.

  3. Middleware is used for parsing bodies, logging, authentication, CORS and rate limiting, and runs in the order it is registered.

4. How do you create a basic Express server?

Install express, create an app with express(), add middleware such as express.json(), define routes and call app.listen with a port, ideally read from process.env.PORT.

import express from 'express';

const app = express();
app.use(express.json());

app.get('/api/users/:id', async (req, res) => {
  const user = await findUser(req.params.id);
  if (!user) return res.status(404).json({ error: 'Not found' });
  res.json(user);
});

app.listen(process.env.PORT || 3000);

5. What is the difference between req.params, req.query and req.body?

req.params holds route parameters from the URL path, such as id in /users/:id. req.query holds query string values, such as page and sort in /users?page=2&sort=name, and is used for filtering and pagination. req.body holds data sent in the request body, such as JSON from a form or API client, and needs a body-parsing middleware such as express.json().

6. Which response methods does Express provide?

res.json() sends JSON, res.send() sends a string, buffer or object, res.status() sets the status code and can be chained, res.redirect() redirects, res.sendFile() and res.download() send files, res.set() sets headers, res.cookie() sets cookies, and res.end() ends the response without data. Each request must get exactly one response.

7. How do you serve static files?

Answer flow · 3 steps
  1. express.static serves files from a folder, such as app.use(express.static("public")), so public/logo.png is available at /logo.png.

  2. A path prefix can be added with app.use("/assets", express.static("public")), and options set cache headers.

  3. In production, static files are often served by a CDN or Nginx instead.

8. What is the difference between app.use and app.get?

app.use mounts middleware or a router for every HTTP method on a path and everything under it, so app.use("/api", router) handles /api/anything. app.get, app.post and similar handle a specific method and an exact route pattern. app.use is used for middleware such as logging and authentication; method-specific functions are used for endpoints.

9. What does next() do?

Answer flow · 3 steps
  1. next() passes control to the next matching middleware or route handler.

  2. If a middleware neither sends a response nor calls next, the request hangs.

  3. Calling next(err) with an error skips normal handlers and goes to the error-handling middleware. next("route") skips the remaining handlers of the current route.

10. What is express.Router?

express.Router() creates a mini-app with its own routes and middleware, which you mount on a path with app.use. It lets you split an API into modules, such as users, orders and products, each in its own file, and apply middleware, such as authentication, only to a group of routes.

11. How do you read JSON and form data?

Answer flow · 3 steps
  1. app.use(express.json()) parses JSON bodies into req.body, and app.use(express.urlencoded({ extended: true })) parses HTML form submissions.

  2. Both accept a limit option to reject very large bodies.

  3. File uploads with multipart/form-data need extra middleware such as multer.

Intermediate Express.js interview questions

Applied problems, trade-offs and questions about your own projects.

12. How do you handle errors in Express?

Answer flow · 3 steps
  1. I define an error-handling middleware with four arguments, (err, req, res, next), registered after all routes, which logs the error and sends a consistent JSON response with the right status code.

  2. Routes pass errors with next(err).

  3. In Express 5, rejected promises in async handlers are passed to the error handler automatically; in Express 4 I wrap async handlers or use express-async-errors.

13. How do you implement JWT authentication in Express?

Answer flow · 3 steps
  1. On login I verify the password hash, then sign a short-lived access token with jsonwebtoken containing the user id and role, and often a longer refresh token stored in an HttpOnly, secure cookie.

  2. An auth middleware reads the token from the Authorization header or cookie, verifies it and attaches the user to req.

  3. Role-check middleware protects admin routes, and refresh tokens can be rotated and revoked.

14. How do you validate request data?

Answer flow · 3 steps
  1. I validate body, params and query at the edge of each route with a schema, using Zod, Joi or express-validator, in a reusable validation middleware that returns 400 with clear messages when validation fails.

  2. Validating early means the rest of the code can trust its inputs.

  3. I also strip unknown fields to avoid mass assignment.

15. How would you structure a large Express project?

Answer flow · 3 steps
  1. I organise by feature or layer: routes define URLs, controllers handle HTTP details, services hold business logic, and repositories or models talk to the database.

  2. Configuration, middleware and utilities live separately.

  3. This keeps controllers thin, makes services testable without HTTP, and makes it easy to find code.

16. Why does middleware order matter in Express?

Answer flow · 3 steps
  1. Middleware runs in the order it is registered.

  2. Body parsers must come before routes that read req.body, CORS and security headers should come early, authentication must run before protected routes, routes come next, then a 404 handler, and the error-handling middleware must be last.

  3. Registering things in the wrong order is a common source of bugs.

17. How do you enable CORS in Express?

Answer flow · 3 steps
  1. Use the cors package and configure it strictly: allow only your frontend origins, the methods and headers you need, and credentials: true only if cookies are sent, in which case the origin cannot be "*".

  2. It must also answer preflight OPTIONS requests, which the package handles.

  3. Allowing every origin is acceptable only for truly public APIs.

18. How do you handle file uploads in Express?

Answer flow · 3 steps
  1. Use multer as route middleware, for example upload.single("avatar"), with memory or disk storage, or a storage engine that streams to S3.

  2. Set limits on file size and number, filter by MIME type and check file contents, rename files, and never serve uploads from a path that can execute code.

  3. For large files, pre-signed URLs let the browser upload directly to cloud storage.

19. How do sessions and cookies work in Express?

cookie-parser reads cookies into req.cookies, and res.cookie sets them with options such as httpOnly, secure, sameSite and maxAge. express-session stores session data on the server, in Redis or a database in production, and keeps only a signed session ID in the cookie. Sessions should be regenerated after login to prevent session fixation.

20. How do you add rate limiting?

Answer flow · 3 steps
  1. Use express-rate-limit with a window and a maximum number of requests, applied globally or with stricter limits on sensitive routes such as login and password reset.

  2. When running several servers, store counters in Redis so limits are shared.

  3. Return 429 Too Many Requests with a Retry-After header, and set trust proxy correctly behind a load balancer so the real client IP is used.

21. How do you log requests in Express?

morgan provides simple access logs, and pino-http gives fast structured JSON logs with method, URL, status code, response time and a request ID. I attach a request ID to every log line, avoid logging sensitive data such as passwords and tokens, and send logs to a central platform where they can be searched.

22. How do you implement pagination and filtering in an API?

Answer flow · 3 steps
  1. Read page and limit, or a cursor, from req.query, validate them and set a maximum limit.

  2. Offset pagination (LIMIT and OFFSET) is simple but slows down on large tables and can skip items when data changes; cursor pagination using the last item's ID or timestamp is faster and stable.

  3. Return the items plus metadata such as the next cursor or total count, and whitelist filter and sort fields.

High level Express.js interview questions

System design, deep internals, leadership and tough follow-ups.

23. How do you secure an Express application?

I use helmet for security headers, strict CORS, rate limiting with express-rate-limit, input validation, parameterised queries, and secure cookies (HttpOnly, Secure, SameSite). I limit body size, disable the X-Powered-By header, never expose stack traces in production, keep secrets in environment variables, and keep dependencies updated.

24. How do you test an Express API?

Answer flow · 3 steps
  1. Unit tests cover services with Jest or Vitest, mocking the database.

  2. Integration tests use Supertest to send real HTTP requests to the app without starting a server, checking status codes, bodies and headers, ideally against a test database run in Docker.

  3. I export the app separately from the server.listen call so tests can import it.

25. How does Express compare with NestJS and Fastify?

Answer flow · 4 steps
  1. Express is minimal and flexible but leaves structure up to you.

  2. NestJS is an opinionated framework built on Express or Fastify, with modules, dependency injection, decorators and TypeScript, which suits large teams.

  3. Fastify is a faster, schema-based framework with built-in validation and serialisation.

  4. I choose based on the team size, the need for structure and performance requirements.

26. What changed in Express 5?

Answer flow · 3 steps
  1. Express 5 automatically passes rejected promises from async handlers to the error-handling middleware, so wrappers are no longer needed.

  2. It requires Node.js 18 or later, updates path matching (for example wildcards must be named and regular expressions in strings are no longer supported), removes deprecated methods such as res.send(status), and makes req.query read-only.

  3. Upgrades need routes checked against the new syntax.

27. How do you connect Express to a database properly?

Answer flow · 3 steps
  1. Create one database client or connection pool at start-up and reuse it, never a new connection per request.

  2. Use an ORM or query builder such as Prisma, Drizzle, Sequelize or Mongoose, or a driver with parameterised queries.

  3. Keep data access in a repository or service layer, handle connection errors and timeouts, run migrations in deployment, and close the pool on shutdown.

28. How do you make an Express app production-ready?

Set NODE_ENV=production, run behind a reverse proxy or load balancer with HTTPS, set trust proxy, use helmet, CORS, rate limiting and input validation, add structured logging and error tracking, expose health and readiness endpoints, handle graceful shutdown, run several instances (containers or PM2), and keep secrets in environment variables or a secrets manager.

29. How do you document and version an Express API?

Answer flow · 3 steps
  1. Describe the API with an OpenAPI specification, either written by hand or generated from code or validation schemas, and serve interactive docs with Swagger UI or Redoc.

  2. Version through the URL, such as /v1, or headers, keep old versions running while clients migrate, and announce deprecations.

  3. Generated client SDKs and contract tests keep docs and code in sync.

30. How do you improve Express performance?

Answer flow · 3 steps
  1. Profile first.

  2. Common gains come from avoiding synchronous and CPU-heavy work in request handlers, caching responses and database results in Redis, adding database indexes, compressing responses (or letting the proxy do it), setting cache headers for static content, streaming large responses, running one process per CPU core, and moving slow jobs to background queues.

  3. For very high throughput, Fastify is faster.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a backend developer interview?

See all Backend Developer interview questions, covering Node.js, Express.js, NestJS, Python, Django and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields