0
0
Expressframework~5 mins

req.params for route parameters in Express

Choose your learning style9 modes available
Introduction

req.params lets you get values from the URL path in Express. It helps your app know what the user wants based on the URL.

When you want to get an ID from the URL like /user/123 to find a user.
When your route needs to handle different items by name or ID from the URL.
When you want to build URLs that change based on user input or selection.
Syntax
Express
app.get('/route/:paramName', (req, res) => {
  const value = req.params.paramName;
  // use value
});

Use a colon (:) before the parameter name in the route path.

Access the parameter value with req.params.paramName.

Examples
This route gets the user ID from the URL like /user/5 and sends it back.
Express
app.get('/user/:id', (req, res) => {
  res.send(`User ID is ${req.params.id}`);
});
This route gets two parameters from the URL, showing how to handle multiple route params.
Express
app.get('/post/:postId/comment/:commentId', (req, res) => {
  res.send(`Post ${req.params.postId}, Comment ${req.params.commentId}`);
});
Sample Program

This Express app listens on port 3000. It has a route /product/:productId that reads the productId from the URL and sends it back in the response.

Express
import express from 'express';
const app = express();
const port = 3000;

app.get('/product/:productId', (req, res) => {
  const productId = req.params.productId;
  res.send(`Product ID requested: ${productId}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Route parameters are always strings. Convert them if you need numbers.

If the URL does not match the route pattern, req.params will be empty.

You can have multiple parameters in one route, each with its own name.

Summary

req.params gets values from the URL path in Express routes.

Use a colon before the parameter name in the route path.

Access parameters with req.params.paramName inside the route handler.