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.queryinstead ofreq.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
| Concept | Description | Example |
|---|---|---|
| Route Parameter | Dynamic part of URL defined with colon | /user/:id |
| Access Parameter | Use req.params to get value | req.params.id |
| Multiple Parameters | Define multiple with colons | /post/:postId/comment/:commentId |
| Optional Parameter | Add ? to make optional | /user/:id? |
| Parameter Validation | Check and sanitize before use | Use 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.