Express Routing

Routing determines how your app responds when a client requests a specific URL. In Express, you define routes by calling a method on the app object.

app.METHOD(path, handler)
  • METHOD: the HTTP method in lowercase (get, post, put, delete)
  • path: the URL path (a string or regular expression)
  • handler: a callback function called when the route matches

HTTP methods

// GET request to /
app.get('/', (req, res) => {
  res.send('Hello World');
});

// POST request to /
app.post('/', (req, res) => {
  res.send('Got a POST request');
});

// PUT request to /user
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user');
});

// DELETE request to /user
app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user');
});

Route parameters

Route parameters are named segments of the URL. They are prefixed with : in the path and available on req.params.

// GET /user/123
app.get('/user/:id', (req, res) => {
  const { id } = req.params;
  res.send(`User ID is ${id}`);
});

You can have multiple parameters:

// GET /posts/2024/nodejs
app.get('/posts/:year/:slug', (req, res) => {
  const { year, slug } = req.params;
  res.send(`Year: ${year}, Slug: ${slug}`);
});

Query strings

Query strings come after ? in the URL. They are available on req.query.

// GET /search?q=express&limit=10
app.get('/search', (req, res) => {
  const { q, limit } = req.query;
  res.send(`Searching for "${q}", limit: ${limit}`);
});

Route path patterns

Route paths can use wildcards and regular expressions.

// Match any path starting with /users/
app.get('/users/*', (req, res) => {
  res.send('A users route');
});

// Match any path ending with "hello"
app.get(/.*hello$/, (req, res) => {
  res.send('Ends with hello');
});

Within a route handler

Inside a route, you can do anything: query a database, load a file, call an external API, and return the result. The req object contains what the client sent; the res object is how you respond.

See Request Object and Response Object for the full details.