Skip to content
jshacks.dev
TypeScript

Type Express request params and body

Pass type arguments to an Express route for params, response body and request body, so req.params.id and req.body.name are typed. Express 5.

1 min read
Summarize in AI

In an untyped handler, req.body is any. The route methods in @types/express take type arguments for each part of the exchange.

server.tsTypeScript
import express from 'express';

type Params = { id: string };
type Body = { name: string };
type Reply = { id: string; name: string };

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

app.put<Params, Reply, Body>('/users/:id', (req, res) => {
  res.json({ id: req.params.id, name: req.body.name });
});

app.listen(3000);
Text
$ curl -X PUT localhost:3000/users/7 -H 'content-type: application/json' -d '{"name":"Ada"}'
{"id":"7","name":"Ada"}

The three type arguments are the route parameters, the response body and the request body. With them req.params.id is a string, req.body.name is a string, and res.json accepts only a Reply, so a typo in the response is a compile error. The order comes from the Request generic in the [@types/express-serve-static-core](https://www.npmjs.com/package/@types/express-serve-static-core) package.

These types are a claim, not a check. Express does not validate the body: a client can send {} and req.body.name is undefined at runtime. In Express 5, req.body is also undefined when no body parser matched. Validate with a schema at the edge, then rely on the type.

Also inNode.js
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.