Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you return a custom 404 response for unknown routes in Express?

SHORT ANSWER

Add a middleware with no path after all your routes. If no earlier route replied, the request reaches it, and you send a 404 status with a JSON or HTML body.

Explain it simply

At a railway enquiry desk, if none of the specific counters can help you, the last counter says, "No such train." The 404 handler is that last counter. It works only because it sits at the end: any request that no earlier route answered falls through to it.

Example

js
const express = require("express");
const app = express();

app.get("/api/notices", (req, res) => res.json([]));

// 404 handler: no path, registered after every route
app.use((req, res) => {
  res.status(404).json({
    error: "Not found",
    path: req.originalUrl,
  });
});

// optional: error handler after it
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});

app.listen(3000);

Points to know:

  • Express has a default 404 page, but it is plain HTML, which is awkward for an API client expecting JSON.
  • A 404 is not an error to Express: nothing throws. The error handler runs only when next(err) is called.
  • For a missing resource inside a route, such as a student ID that is not in the database, reply with 404 right there.
  • A single-page app often sends index.html for unknown non-API paths instead.

What to say in the interview

"I add a catch-all middleware after the routes that responds with 404 and a JSON body. Then comes the error handler for real failures. The order is what makes the fallback work."

Common mistakes

  • Putting the catch-all above the routes, which makes every request return 404.
  • Returning 200 with an error message for a missing resource.

#express#routing#error-handling

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.