Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 43 ยท Practice and Review

Exercises with Solutions

Practice Express.js with five graded exercises on routing, middleware, validation, error handling and API-key auth. Each has a hint and a runnable solution.

Reading about Express is not the same as writing it. This lesson gives you five exercises that grow from a single route to a small protected API. Each one has a task, a hint and a solution you can run. Try the task on your own first, then compare.

Because Express cannot be installed in your browser, the runnable solutions use the mini Express from Inside Express. It has the same shape (app.use, app.get, req.params, res.json, next(), four-argument error handlers). On your own machine you would use the real package, and the handler bodies stay the same. The real Express version of each solution is shown read-only where it differs.

Five exercises

Routing A route with a parameter and a JSON 404.
Middleware Tag every request with an ID.
Validation Reject bad input with a 422.
Errors One handler for every failure.

Auth with an API key is exercise five.

1 / 2

Exercise 1: a route and a JSON 404

Task. Make GET /greet/:name answer with { "message": "Hello, <name>!" }. Any other request should get a JSON 404 of the form { "error": "No route for METHOD /path" } instead of the default text.

Hint. Route parameters live in req.params. A handler with no path, registered after every route, only runs when nothing else matched.

Exercise 2: tag every request

Task. Add a middleware that gives each request an ID (req-1, req-2, ...), stores it on req.id and sends it back in an x-request-id response header.

Hint. Middleware must call next(), and it must be registered before the routes it should affect.

Node.js Solutions to exercises 1 and 2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You should see request IDs counting up, the two greetings, and JSON 404s for the unknown path and for the wrong method. Notice that DELETE /greet/Ada is a 404: the route exists, but only for GET.

In real Express the same solution reads almost identically:

JavaScript
import express from 'express';

const app = express();
let counter = 0;

app.use((req, res, next) => {
  req.id = `req-${++counter}`;
  res.set('x-request-id', req.id);
  next();
});

app.get('/greet/:name', (req, res) => {
  res.json({ message: `Hello, ${req.params.name}!` });
});

app.use((req, res) => {
  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
});

Exercise 3: validate input

Task. Add POST /users. The JSON body needs a name (non-empty string) and an age (integer from 0 to 150). If anything is wrong, respond 422 with { "error": "Validation failed", "details": [ ...messages ] }. Otherwise respond 201 with the created user.

Hint. Write a plain function that returns a list of messages, and treat an empty list as valid. See Validating Input for schema libraries that do this for you.

Exercise 4: one error handler for everything

Task. Define an HttpError class with a status. Throw it from handlers, and add one four-argument error handler that turns it into JSON. Unknown errors must become a generic 500 that does not leak the original message.

Hint. The error handler goes after all routes. Read Error Handling if the four-parameter rule is unfamiliar.

Exercise 5: protect a route with an API key

Task. Require an x-api-key header on POST /users. No header means 401; a wrong key means 403. The key for this exercise is secret-123.

Hint. An auth guard is middleware you pass per route: app.post('/users', requireKey, handler). It calls next() only when the key is good.

Node.js Solutions to exercises 3, 4 and 5

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the order of the responses: no key gives 401, a wrong key gives 403, bad data (with a good key) gives 422 with two messages, and a valid request gives 201. The /crash route shows why the handler's generic message matters: the secret in the thrown error never reaches the client.

Stretch goals

When these five feel easy, extend the same app:

  1. Add GET /users/:id backed by an in-memory Map, and throw HttpError(404, ...) for unknown ids.
  2. Move the routes into a router, as in Modular Routing, and mount it at /api/v1.
  3. Write a rateLimit(max) middleware factory that answers 429 after max requests (a stand-in appears in Security Best Practices).
  4. Turn the API-key guard into a factory, requireKey(allowedKeys), as shown in Writing Your Own Middleware.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must a catch-all 404 handler be registered?

    Layers run in registration order, so a catch-all placed first would answer every request before the real routes were tried.
  2. 2. Which status code fits a request whose JSON body is well-formed but has invalid values?

    422 (Unprocessable Content) means the syntax was fine but the data failed validation. 400 is also common for malformed requests.
  3. 3. What identifies an Express error handler?

    Express checks the function's parameter count. (err, req, res, next) makes it an error handler.
  4. 4. A request has no API key at all. Which status should the guard send?

    401 means "not authenticated" (no credentials), while 403 means "credentials understood but not allowed".

Summary

  • Routes, middleware, validation, error handling and auth are small pieces that compose in registration order.
  • Register shared middleware first, the 404 fallback after the routes and the error handler last.
  • Validation returns a list of problems; the error handler turns thrown errors into consistent JSON.
  • Use 401 for missing credentials, 403 for refused ones and 422 for invalid data.
  • Never send internal error messages to clients; log them instead.

Next: Express Interview Questions.