How to Get Query String in Express: Simple Guide
In Express, you get the query string parameters from the
req.query object inside your route handler. This object contains key-value pairs of the query parameters sent in the URL after the ? symbol.Syntax
Use req.query inside your route handler to access query parameters. It returns an object where each key is a parameter name and the value is the parameter value as a string.
req: The request object from Express.query: Property holding query parameters as an object.
javascript
app.get('/path', (req, res) => { const queryParams = req.query; res.send(queryParams); });
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) => { const queries = req.query; res.json({ receivedQueries: queries }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
When you visit: http://localhost:3000/search?term=books&sort=asc
Response JSON: {"receivedQueries":{"term":"books","sort":"asc"}}
Common Pitfalls
Common mistakes when getting query strings in Express include:
- Trying to parse
req.urlmanually instead of usingreq.query. - Expecting query parameters to be automatically converted to numbers or booleans (they are always strings).
- Not handling missing or undefined query parameters, which can cause errors if you assume they exist.
Always check if a query parameter exists before using it.
javascript
app.get('/example', (req, res) => { // Wrong: manually parsing URL string // const url = req.url; // const queryString = url.split('?')[1]; // Right: use req.query const page = req.query.page || '1'; // default to '1' if missing res.send(`Page number is ${page}`); });
Quick Reference
Summary tips for getting query strings in Express:
- Use
req.queryto get query parameters as an object. - Query values are always strings; convert them if needed.
- Check for undefined parameters before using them.
- Express parses query strings automatically; no extra parsing needed.
Key Takeaways
Access query parameters in Express using the req.query object inside route handlers.
Query parameters are strings; convert them explicitly if you need numbers or booleans.
Always check if a query parameter exists before using it to avoid errors.
Express automatically parses the query string; manual parsing is unnecessary.
Use default values to handle missing query parameters gracefully.