How to Get Query Params in Express: Simple Guide
In Express, you get query parameters from the
req.query object inside your route handler. Each query parameter is available as a key-value pair, where keys are parameter names and values are strings.Syntax
Use req.query inside your route handler to access query parameters sent in the URL. It returns an object with keys as parameter names and values as strings.
req: The request object.query: Property holding query parameters.
javascript
app.get('/path', (req, res) => { const params = req.query; res.send(params); });
Example
This example shows a simple Express server that reads query parameters from the URL and sends them back as JSON.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/search', (req, res) => { // Access query parameters const { term, page } = req.query; res.json({ term, page }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
// When visiting: http://localhost:3000/search?term=books&page=2
// Response JSON: {"term":"books","page":"2"}
Common Pitfalls
Common mistakes include:
- Trying to access query params from
req.paramswhich is for route parameters, not query strings. - Expecting query parameters to be automatically converted to numbers or booleans; they are always strings.
- Not handling missing or undefined query parameters.
javascript
/* Wrong way: Using req.params for query params */ app.get('/search', (req, res) => { // This will be undefined for query params const term = req.params.term; res.send(term); }); /* Right way: Use req.query */ app.get('/search', (req, res) => { const term = req.query.term; res.send(term || 'No term provided'); });
Quick Reference
Summary tips for using query parameters in Express:
- Access query params with
req.query. - All values are strings; convert types if needed.
- Check if params exist before using them.
- Use URL encoding for special characters in query strings.
Key Takeaways
Use
req.query to get query parameters in Express route handlers.Query parameters are always strings; convert them if you need other types.
Do not confuse
req.query with req.params which is for route parameters.Always check if a query parameter exists before using it to avoid errors.
Encode special characters in URLs to ensure query parameters are parsed correctly.