Express.js – route parameters

In this article, we would like to show you how to use route parameters in Express.js.

Introduction

Route parameters are named URL segments that are used to get the values specified at their position in the URL. The received values are stored in the req.params object, with the name of the route parameter specified in the path as their respective keys.

route path: /users/:id/
request URL: http://localhost:5000/users/74
req.params: { "id": "74" }

Practical example

In below example, we define route for users with specified route parameter used get user by id. For now we just use it to send back the parameter (req.params).

const express = require('express');

const app = express();

app.get('/users/:id', (req, res) => {
  res.send(req.params); // send back the parameter
});

app.listen(5000);

Result:

Node.js / Express.js - server response
Node.js / Express.js – server response

As you can see, we passed 12 as a user id parameter and received proper req.params object as a response.

Note:

The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).

References