0
0
ExpressHow-ToBeginner · 3 min read

How to Use Route Parameters in Express: Simple Guide

In Express, you use route parameters by defining them with a colon prefix in the route path, like /user/:id. You can then access these parameters inside your route handler via req.params to get dynamic values from the URL.
📐

Syntax

Route parameters are defined in the route path by prefixing a segment with a colon (:). This segment acts as a placeholder for dynamic values in the URL.

  • /user/:id: id is a route parameter.
  • req.params.id: Accesses the value passed in place of :id.
javascript
app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID is ${userId}`);
});
💻

Example

This example shows a simple Express server that uses a route parameter id to respond with a message containing the user ID from the URL.

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

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

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000 When you visit http://localhost:3000/user/123, the browser shows: User ID is 123
⚠️

Common Pitfalls

Common mistakes when using route parameters include:

  • Forgetting the colon (:) before the parameter name in the route path.
  • Trying to access parameters from req.query instead of req.params.
  • Not handling cases where the parameter might be missing or invalid.

Always validate and sanitize route parameters before using them.

javascript
/* Wrong: Missing colon, so no parameter captured */
app.get('/user/id', (req, res) => {
  res.send(req.params.id); // undefined
});

/* Right: Use colon to define parameter */
app.get('/user/:id', (req, res) => {
  res.send(req.params.id); // correct value
});
📊

Quick Reference

ConceptDescriptionExample
Route ParameterDynamic part of URL defined with colon/user/:id
Access ParameterUse req.params to get valuereq.params.id
Multiple ParametersDefine multiple with colons/post/:postId/comment/:commentId
Optional ParameterAdd ? to make optional/user/:id?
Parameter ValidationCheck and sanitize before useUse middleware or manual checks

Key Takeaways

Define route parameters with a colon prefix in the route path.
Access parameters inside handlers using req.params.parameterName.
Always validate route parameters to avoid errors or security issues.
Multiple parameters can be used in one route for complex URLs.
Optional parameters can be defined by adding a question mark after the name.