Backend & APIs

Express.js interview questions

Interviewers often probe a candidate's understanding of Express.js's core architecture, particularly middleware, routing, and request/response handling. They look for the ability to build robust, scalable, and secure APIs, along with practical knowledge of error handling and performance considerations.

16 questions (4 easy · 6 medium · 6 hard), each with what a strong answer covers and where people lose the point. Free to read, no account.

On this page (16 questions)
  1. 1.How do you set up a basic Express.js server that listens on port 3000 and responds with 'Hello World!' to a GET request at the root path?
  2. 2.What is the fundamental difference between `app.get()` and `app.post()` in Express.js, and when would you use each?
  3. 3.Explain the purpose of the `req` and `res` objects in an Express.js route handler.
  4. 4.How do you serve static files (like HTML, CSS, JavaScript, images) in an Express.js application?
  5. 5.Explain what middleware is in Express.js and how it works within the request-response cycle.
  6. 6.Write a custom middleware function that logs the HTTP method and URL of every incoming request to the console. Demonstrate how to apply it globally.
  7. 7.Differentiate between route parameters (`req.params`) and query strings (`req.query`) in Express.js, providing an example for each.
  8. 8.How do you implement custom error handling middleware in Express.js? Provide a basic example.
  9. 9.Explain the purpose of `express.Router()` and when you would use it in an Express.js application.
  10. 10.What is the `next()` function in Express.js middleware, and why is it important?
  11. 11.How do you handle asynchronous errors in Express.js middleware or route handlers to ensure they are caught by your error handling middleware?
  12. 12.Describe the importance of middleware order in an Express.js application. Provide an example where order matters significantly.
  13. 13.Design a simple authentication middleware that checks for an 'Authorization' header with a specific API key. If the key is missing or incorrect, it should send a 401 Unauthorized response.
  14. 14.What are some common security headers you would implement in an Express.js application, and why are they important?
  15. 15.When would you use global middleware versus route-specific middleware in an Express.js application? Provide examples for each scenario.
  16. 16.Outline the key design considerations for building a RESTful API using Express.js, including routing, data validation, and error handling.

1.How do you set up a basic Express.js server that listens on port 3000 and responds with 'Hello World!' to a GET request at the root path?

Warm-up

What a strong answer covers

  • Import the Express module using `require('express')`.
  • Create an Express application instance by calling `express()`.
  • Define a GET route for the root path ('/') using `app.get()`.
  • Inside the route handler, use `res.send('Hello World!')` to send the response.
  • Start the server using `app.listen(3000, callback)` to listen on port 3000.

Where people lose the point

  • Forgetting to call `app.listen()` to start the server.
  • Not sending a response using `res.send()` or similar, causing the request to hang.
  • Incorrectly defining the route path or HTTP method.
Link to this question

2.What is the fundamental difference between `app.get()` and `app.post()` in Express.js, and when would you use each?

Warm-up

What a strong answer covers

  • `app.get()` defines a route handler for HTTP GET requests, typically used for retrieving data from the server.
  • `app.post()` defines a route handler for HTTP POST requests, typically used for submitting data to the server to create a new resource.
  • GET requests send data via URL query parameters, while POST requests send data in the request body.
  • GET requests are generally idempotent and cacheable, whereas POST requests are not.

Where people lose the point

  • Confusing the purpose of GET (retrieve) and POST (create/submit).
  • Incorrectly stating that GET requests can have a body (they technically can, but it's not standard practice and often ignored).
  • Not mentioning idempotency or cacheability as key differentiators.
Link to this question

3.Explain the purpose of the `req` and `res` objects in an Express.js route handler.

Warm-up

What a strong answer covers

  • The `req` (request) object represents the incoming HTTP request from the client.
  • It contains properties like `req.params`, `req.query`, `req.body`, `req.headers`, and `req.method` to access request data.
  • The `res` (response) object represents the HTTP response that the server sends back to the client.
  • It provides methods like `res.send()`, `res.json()`, `res.status()`, and `res.redirect()` to construct and send the response.

Where people lose the point

  • Confusing which object is for incoming data (`req`) and which is for outgoing data (`res`).
  • Listing properties/methods that belong to the wrong object.
  • Providing a vague explanation without specific examples of properties or methods.
Link to this question

4.How do you serve static files (like HTML, CSS, JavaScript, images) in an Express.js application?

Warm-up

What a strong answer covers

  • Use the built-in `express.static()` middleware function.
  • Pass the path to your static assets directory (e.g., 'public') to `express.static()`.
  • Mount this middleware using `app.use()` at the desired path (e.g., `app.use(express.static('public'))`).
  • Optionally, provide a virtual path prefix (e.g., `app.use('/static', express.static('public'))`) to access files via `/static/image.png`.

Where people lose the point

  • Forgetting to use `app.use()` to register the static middleware.
  • Providing an incorrect or relative path to the static directory.
  • Trying to manually create routes for each static file type.
Link to this question

5.Explain what middleware is in Express.js and how it works within the request-response cycle.

Core

What a strong answer covers

  • Middleware functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` middleware function.
  • They can execute code, make changes to `req` and `res` objects, end the request-response cycle, or call `next()` to pass control to the next middleware.
  • Middleware functions are executed in the order they are defined, forming a pipeline.
  • They are used for tasks like logging, authentication, parsing request bodies, and serving static files.

Where people lose the point

  • Omitting the `next()` function's role in passing control.
  • Not emphasizing the sequential execution order of middleware.
  • Confusing middleware with simple route handlers.
Link to this question

6.Write a custom middleware function that logs the HTTP method and URL of every incoming request to the console. Demonstrate how to apply it globally.

Core

What a strong answer covers

  • Define a function `loggerMiddleware(req, res, next)`.
  • Inside the function, use `console.log(`${req.method} ${req.url}`);` to log the method and URL.
  • Crucially, call `next()` at the end of the middleware function to pass control to the next handler.
  • Apply it globally using `app.use(loggerMiddleware);` before any routes or other middleware.

Where people lose the point

  • Forgetting to call `next()` within the middleware, which would cause requests to hang.
  • Not including `req`, `res`, and `next` as parameters in the middleware function signature.
  • Applying the middleware after routes, meaning it wouldn't catch all requests.
Link to this question

7.Differentiate between route parameters (`req.params`) and query strings (`req.query`) in Express.js, providing an example for each.

Core

What a strong answer covers

  • Route parameters (`req.params`) are part of the URL path, used to capture specific values from the URL segments (e.g., `/users/:id`). They are defined with a colon prefix in the route path.
  • Query strings (`req.query`) are appended to the URL after a question mark (?), used for optional parameters or filtering (e.g., `/products?category=electronics&sort=price`). They are key-value pairs.
  • Example for `req.params`: Route `/users/:userId` for URL `/users/123` results in `req.params.userId = '123'`.
  • Example for `req.query`: Route `/search` for URL `/search?q=express&limit=10` results in `req.query.q = 'express'` and `req.query.limit = '10'`.

Where people lose the point

  • Confusing the syntax or purpose of route parameters vs. query strings.
  • Incorrectly accessing the values (e.g., trying to get `req.query.id` from a route parameter).
  • Not providing clear, distinct examples for both.
Link to this question

8.How do you implement custom error handling middleware in Express.js? Provide a basic example.

Core

What a strong answer covers

  • Custom error handling middleware functions have four arguments: `(err, req, res, next)`.
  • Express recognizes this signature and routes errors to it automatically.
  • Place error handling middleware after all other `app.use()` and route calls.
  • Example: `app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });`

Where people lose the point

  • Forgetting the `err` argument, making it a regular middleware instead of an error handler.
  • Placing the error middleware before regular routes, preventing it from catching errors from those routes.
  • Not sending a response or calling `next()` in the error handler, causing the request to hang.
Link to this question

9.Explain the purpose of `express.Router()` and when you would use it in an Express.js application.

Core

What a strong answer covers

  • `express.Router()` creates a new router object, which is a complete middleware and routing system.
  • It allows you to define routes and middleware for a specific part of your application in a modular way.
  • You would use it to organize your application into logical, maintainable modules (e.g., separate routers for 'users', 'products', 'auth').
  • Routers are then 'mounted' onto specific base paths in the main application using `app.use('/api/users', usersRouter)`.

Where people lose the point

  • Confusing `express.Router()` with the main `app` object.
  • Not explaining the benefit of modularity and organization.
  • Incorrectly describing how a router is integrated into the main application.
Link to this question

10.What is the `next()` function in Express.js middleware, and why is it important?

Core

What a strong answer covers

  • The `next()` function is the third argument passed to an Express.js middleware function.
  • Its purpose is to pass control to the next middleware function in the stack or to the next route handler.
  • If a middleware function does not end the request-response cycle (e.g., by sending a response with `res.send()`), it *must* call `next()` to ensure the request continues processing.
  • Failing to call `next()` will cause the request to hang indefinitely, as the server will not know to proceed.

Where people lose the point

  • Not emphasizing that `next()` is crucial for continuing the request-response cycle.
  • Incorrectly stating that `next()` is only for error handling (it's also for normal flow).
  • Failing to mention the consequence of not calling `next()` (request hanging).
Link to this question

11.How do you handle asynchronous errors in Express.js middleware or route handlers to ensure they are caught by your error handling middleware?

Hard

What a strong answer covers

  • Asynchronous errors (e.g., from Promises, `async/await`) are not automatically caught by Express's default error handler or custom error middleware if not explicitly passed.
  • For `async/await` functions, wrap the asynchronous code in a `try-catch` block and call `next(error)` in the `catch` block.
  • Alternatively, use a utility like `express-async-handler` or a custom wrapper function to automatically catch promise rejections and pass them to `next()`.
  • Ensure your custom error handling middleware is defined with four arguments `(err, req, res, next)` to process these errors.

Where people lose the point

  • Assuming `async/await` errors are automatically handled without `try-catch` or a wrapper.
  • Not calling `next(error)` when an asynchronous error occurs, leading to unhandled promise rejections.
  • Confusing synchronous error handling with asynchronous error handling.
Link to this question

12.Describe the importance of middleware order in an Express.js application. Provide an example where order matters significantly.

Hard

What a strong answer covers

  • Express.js executes middleware functions sequentially in the order they are defined using `app.use()` or `app.METHOD()`.
  • Middleware functions can modify the request/response objects or terminate the request-response cycle, so their position determines when these actions occur.
  • If a middleware function that sends a response (e.g., `res.send()`) is placed before another middleware or route, the subsequent ones will never be executed for that request.
  • Example: A body-parser middleware *must* come before any route handler that attempts to read `req.body`, otherwise `req.body` will be undefined. Similarly, an authentication middleware should come before protected routes.

Where people lose the point

  • Understating the critical nature of middleware order, implying it's merely a suggestion.
  • Failing to provide a concrete example where incorrect order leads to functional issues.
  • Not mentioning that middleware can terminate the cycle, preventing subsequent execution.
Link to this question

13.Design a simple authentication middleware that checks for an 'Authorization' header with a specific API key. If the key is missing or incorrect, it should send a 401 Unauthorized response.

Hard

What a strong answer covers

  • Define a middleware function `authenticateApiKey(req, res, next)`.
  • Inside, retrieve the 'Authorization' header using `req.headers.authorization`.
  • Check if the header exists and if its value matches a predefined `SECRET_API_KEY`.
  • If valid, call `next()` to proceed; otherwise, send `res.status(401).send('Unauthorized: Invalid API Key')`.
  • Demonstrate how to apply this middleware to a specific route or globally using `app.use()`.

Where people lose the point

  • Forgetting to call `next()` when authentication is successful, causing requests to hang.
  • Not setting the correct HTTP status code (401 Unauthorized).
  • Exposing the `SECRET_API_KEY` directly in the code without considering environment variables.
Link to this question

14.What are some common security headers you would implement in an Express.js application, and why are they important?

Hard

What a strong answer covers

  • **X-Content-Type-Options: nosniff**: Prevents browsers from MIME-sniffing a response away from the declared content-type, mitigating XSS attacks.
  • **X-Frame-Options: DENY/SAMEORIGIN**: Prevents clickjacking attacks by controlling whether a page can be rendered in an `<iframe>`, `<frame>`, or `<object>`.
  • **Strict-Transport-Security (HSTS)**: Forces clients to connect to the server over HTTPS only, preventing downgrade attacks and cookie hijacking.
  • **Content-Security-Policy (CSP)**: Mitigates XSS by specifying valid sources for content (scripts, styles, images, etc.) that the browser should load.
  • **X-XSS-Protection: 0**: Disables the browser's built-in XSS auditor, as CSP is a more robust solution and the auditor can sometimes introduce vulnerabilities.

Where people lose the point

  • Listing headers without explaining their security purpose.
  • Confusing the purpose of different headers (e.g., X-Frame-Options vs. CSP).
  • Not mentioning the `helmet` middleware as a common way to implement many of these.
Link to this question

15.When would you use global middleware versus route-specific middleware in an Express.js application? Provide examples for each scenario.

Hard

What a strong answer covers

  • **Global Middleware**: Applied to all incoming requests to the application using `app.use()`. It's suitable for tasks that need to run for every request, regardless of the route.
  • **Route-Specific Middleware**: Applied only to specific routes or groups of routes. It's suitable for tasks that are relevant only to certain endpoints.
  • **Global Example**: Logging middleware, body parsing (`express.json()`), security headers (`helmet`), or static file serving (`express.static()`) are typically global.
  • **Route-Specific Example**: Authentication middleware for protected API endpoints, validation middleware for specific data submission routes, or authorization checks for admin-only routes.

Where people lose the point

  • Failing to clearly distinguish the scope of application for each type.
  • Providing examples that could be applied to either, without explaining why one is preferred.
  • Not mentioning that route-specific middleware can be an array of functions.
Link to this question

16.Outline the key design considerations for building a RESTful API using Express.js, including routing, data validation, and error handling.

Hard

What a strong answer covers

  • **Resource-Based Routing**: Design routes around resources (e.g., `/users`, `/products`) using appropriate HTTP methods (GET, POST, PUT, DELETE) for CRUD operations. Utilize `express.Router()` for modularity.
  • **Statelessness**: Ensure each request from a client to server contains all necessary information, with no session state stored on the server between requests.
  • **Data Validation**: Implement input validation (e.g., using libraries like Joi or Express-validator) in middleware before route handlers to ensure data integrity and prevent malicious input.
  • **Consistent Error Handling**: Implement a centralized error handling middleware to catch all errors, log them, and send consistent, informative (but not overly verbose) error responses (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error).
  • **Authentication & Authorization**: Use middleware for authentication (e.g., JWT, API keys) to verify user identity and authorization to check if the user has permission for the requested action.

Where people lose the point

  • Confusing RESTful principles with general API design (e.g., not mentioning statelessness).
  • Omitting crucial aspects like data validation or proper error response formats.
  • Not emphasizing the use of Express.js features like `express.Router()` for organization.
Link to this question
No account needed

Answer one real Express.js question now

A question a Express.js panel actually asks, answered out loud, scored on what you said and how you said it. Under two minutes, and nothing to sign up for.

How do you set up a basic Express.js server that listens on port 3000 and responds with 'Hello World!' to a GET request at the root path?

We never store the audio. Your answer is deleted within 24 hours unless you save the result.

How Express.js answers get judged

The weights a Express.js interviewer is holding, whether or not they say so out loud. Round Zero scores your practice answers against exactly these, and quotes your own words back as the evidence for each.

Technical Accuracy

30%

The answer demonstrates a correct and precise understanding of Express.js concepts, syntax, and best practices. Code examples are functional and free of errors.

Conceptual Depth

25%

The candidate explains not just 'what' but 'why' and 'how' Express.js features work, demonstrating a deep understanding of underlying principles like the request-response cycle and middleware architecture.

Problem Solving & Application

20%

Ability to apply Express.js knowledge to solve practical problems, design solutions, and discuss trade-offs. This includes demonstrating how to structure applications or handle specific scenarios.

Best Practices & Security

15%

Awareness of idiomatic Express.js patterns, security considerations, performance implications, and maintainability. The candidate suggests robust and scalable solutions.

Clarity and Structure

10%

The explanation is clear, concise, well-organized, and easy to follow. Technical terms are used accurately, and complex ideas are broken down effectively.

Related Backend & APIs skills

All skills →

Now say them out loud

You have read what strong Express.js answers contain. The next thing that moves the needle is producing one under time, out loud, and finding out where it falls apart.

  • These questions asked back, with follow-ups
  • Flashcards for the ones you keep missing
  • A scored mock that quotes your own answers

Browse every skill

Practising Express.js: common questions

What Express.js interview questions should I practice?
Start with the core areas Express.js interviewers probe: How do you set up a basic Express.js server that listens on port 3000 and responds with 'Hello World!' to a GET request at the root path; What is the fundamental difference between `app.get()` and `app.post()` in Express.js, and when would you use each; Explain the purpose of the `req` and `res` objects in an Express.js route handler.. This page outlines strong answers and common mistakes, and the scored path drills each one with follow-ups.
Is the Express.js practice free?
Yes. The Express.js path runs free inside Round Zero: lessons, practice questions and flashcards. Drills are unlimited on every plan, free included. So is the full scorecard. Free also covers 3 complete scored interviews, no card.
How is this different from a Express.js question list?
A static list gives you questions with no feedback. Round Zero runs a live scored practice that probes your actual answers, rotates difficulty, and tells you exactly what to fix, grounded in a Express.js rubric.
How should I prepare for a Express.js interview?
Learn the concepts, drill the questions until answers come fast, then prove it in a scored mock. Round Zero sequences all three so you know you are ready, not just that you read about Express.js.
How is a Express.js answer scored?
Express.js answers are scored on technical accuracy, conceptual depth, problem solving & application, best practices & security, clarity and structure, with evidence quoted from what you actually said, so feedback is specific instead of generic praise.