How to Use Optional Parameters in Express Routes
In Express, you can define an optional route parameter by adding a question mark
? after the parameter name in the route path, like /user/:id?. This makes the parameter optional, so the route matches with or without that part in the URL.Syntax
To make a route parameter optional in Express, add a ? after the parameter name in the route path.
:parammeans a required parameter.:param?means an optional parameter.
Express will match the route whether the optional parameter is present or not.
javascript
app.get('/user/:id?', (req, res) => { const id = req.params.id; if (id) { res.send(`User ID is ${id}`); } else { res.send('No User ID provided'); } });
Example
This example shows a route /user/:id? where the id parameter is optional. If you visit /user/123, it shows the ID. If you visit /user without an ID, it shows a different message.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/user/:id?', (req, res) => { const id = req.params.id; if (id) { res.send(`User ID is ${id}`); } else { res.send('No User ID provided'); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
When visiting http://localhost:3000/user/123, response: User ID is 123
When visiting http://localhost:3000/user, response: No User ID provided
Common Pitfalls
One common mistake is forgetting the ? and expecting the parameter to be optional, but Express treats it as required.
Another issue is route order: if you have a route with an optional parameter and another route that matches a similar path, the order of routes matters because Express matches routes in the order they are defined.
javascript
/* Wrong: parameter is required because no ? */ app.get('/product/:id', (req, res) => { res.send(`Product ID: ${req.params.id}`); }); /* Right: parameter is optional with ? */ app.get('/product/:id?', (req, res) => { if (req.params.id) { res.send(`Product ID: ${req.params.id}`); } else { res.send('No Product ID'); } });
Quick Reference
Summary tips for using optional parameters in Express routes:
- Use
:param?to make a parameter optional. - Check
req.params.paramto see if the parameter was provided. - Define more specific routes before routes with optional parameters to avoid conflicts.
- Optional parameters can only be at the end of the route path.
Key Takeaways
Add a question mark after a route parameter name to make it optional, like
:id?.Check if the optional parameter exists in
req.params before using it.Route order matters; place specific routes before optional parameter routes to avoid conflicts.
Optional parameters must be at the end of the route path in Express.