How to Get Route Params in Express: Simple Guide
In Express, you get route parameters using
req.params. Define parameters in your route path with a colon, like /user/:id, then access the value with req.params.id inside your route handler.Syntax
Route parameters are defined in the route path using a colon : followed by the parameter name. Inside the route handler, you access these parameters via req.params, which is an object containing key-value pairs of parameter names and their values.
/path/:paramNamedefines a route parameter namedparamName.req.params.paramNameaccesses the value of that parameter.
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 with a route that captures a user ID from the URL and sends it back in the response.
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 response will be: User ID is 123
Common Pitfalls
Common mistakes when using route params include:
- Forgetting the colon
:before the parameter name in the route path. - Trying to access parameters from
req.queryorreq.bodyinstead ofreq.params. - Not matching the route path exactly, causing the route not to trigger.
Here is an example of a wrong and right way:
javascript
// Wrong: Missing colon in route path app.get('/user/id', (req, res) => { // req.params.id will be undefined res.send(`User ID is ${req.params.id}`); }); // Right: Colon before parameter name app.get('/user/:id', (req, res) => { res.send(`User ID is ${req.params.id}`); });
Quick Reference
| Concept | Usage | Description |
|---|---|---|
| Define param | /path/:param | Use colon before param name in route path |
| Access param | req.params.param | Get value of param inside route handler |
| Multiple params | /user/:id/book/:bookId | Access with req.params.id and req.params.bookId |
| No colon | /user/id | No param, 'id' is literal part of path |
Key Takeaways
Use a colon before the parameter name in the route path to define route params.
Access route parameters inside handlers with req.params.paramName.
Route parameters are part of the URL path, not query strings or body data.
Always match the route path exactly to capture parameters correctly.
You can define multiple route parameters in one path and access each via req.params.