0
0
Expressframework~5 mins

Route parameters in Express

Choose your learning style9 modes available
Introduction

Route parameters let you capture parts of a URL as variables. This helps you handle dynamic content like user profiles or product pages.

When you want to get a user ID from the URL to show their profile.
When you need to fetch a product by its ID from the URL.
When building URLs that change based on the item, like blog posts or articles.
When you want to create routes that accept different values without making many separate routes.
Syntax
Express
app.get('/path/:parameterName', (req, res) => {
  const param = req.params.parameterName;
  res.send(`Value is ${param}`);
});

Route parameters start with a colon : in the route path.

You access the parameter value inside the handler with req.params.parameterName.

Examples
This route captures the id from the URL like /user/123.
Express
app.get('/user/:id', (req, res) => {
  res.send(`User ID is ${req.params.id}`);
});
This route captures two parameters: category and id.
Express
app.get('/product/:category/:id', (req, res) => {
  res.send(`Category: ${req.params.category}, Product ID: ${req.params.id}`);
});
Multiple parameters can be used to get nested data like comments on posts.
Express
app.get('/post/:postId/comment/:commentId', (req, res) => {
  res.send(`Post: ${req.params.postId}, Comment: ${req.params.commentId}`);
});
Sample Program

This simple Express app listens on port 3000. It has one route that takes a userId from the URL and sends it back in the response.

Try visiting http://localhost:3000/user/42 in your browser to see the output.

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

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

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

Route parameters only capture the part of the URL where you put the : placeholder.

If you want to accept optional parameters, you can add a question mark like :param?.

Always validate or sanitize route parameters before using them to avoid security issues.

Summary

Route parameters let you get dynamic values from the URL.

Use req.params to access these values inside your route handler.

This helps build flexible routes for things like user profiles, products, or posts.