How to access query string parameters in Express.js on Node.js?
How can I retrieve GET variables from the query string in Express.js, similar to how $_GET works in PHP?
I know that Node.js provides access to the URL in the request object. What is the proper method to extract and access query string parameters in Express.js applications?
To access query string parameters in Express.js, you use the req.query object which automatically parses URL query parameters into a JavaScript object containing key-value pairs. This object is available in your route handlers and provides a simple, intuitive way to retrieve GET variables from the URL, similar to PHP’s $_GET functionality.
Contents
- Basic Query Parameter Access
- Handling Multiple Values and Arrays
- Nested Parameters and Advanced Features
- Query Parser Configuration Options
- Complete Practical Examples
Basic Query Parameter Access
In Express.js, query string parameters are automatically parsed and made available through the req.query object in your route handlers. This is the standard and recommended approach for accessing GET variables.
Basic Usage Example:
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
// req.query contains all query string parameters
const searchTerm = req.query.q;
const page = req.query.page;
const limit = req.query.limit;
res.send(`Searching for: ${searchTerm}, Page: ${page}, Limit: ${limit}`);
});
app.listen(3000);
For a URL like http://localhost:3000/search?q=express&page=2&limit=10, the req.query object will be:
{
q: 'express',
page: '2',
limit: '10'
}
The Express.js documentation confirms that req.query is the property that contains the parsed query string parameters.
Handling Multiple Values and Arrays
Express.js automatically handles multiple values for the same query parameter by converting them into arrays. This is particularly useful when working with checkboxes or multiple selections.
Multiple Values Example:
app.get('/colors', (req, res) => {
// If URL is /colors?color=red&color=blue&color=green
// req.query will be: { color: ['red', 'blue', 'green'] }
const colors = req.query.color;
console.log(Array.isArray(colors)); // true
res.json({
colors: colors,
count: colors.length
});
});
You can also manually handle arrays using different syntaxes:
Square Bracket Syntax:
// URL: /items?ids[]=1&ids[]=2&ids[]=3
// req.query: { ids: ['1', '2', '3'] }
Comma-Separated Values:
app.get('/tags', (req, res) => {
// URL: /tags?tags=javascript,nodejs,express
const tags = req.query.tags.split(',');
// tags becomes: ['javascript', 'nodejs', 'express']
});
As Stack Overflow explains, when you use the same parameter multiple times, Express automatically creates an array.
Nested Parameters and Advanced Features
Express.js supports nested query parameters using bracket notation, which is useful for complex data structures.
Nested Parameters Example:
app.get('/product', (req, res) => {
// URL: /product?shoe[color]=blue&shoe[size]=42&shirt[color]=red
// req.query will be:
// {
// 'shoe[color]': 'blue',
// 'shoe[size]': '42',
// 'shirt[color]': 'red'
// }
const shoeColor = req.query['shoe[color]'];
const shirtColor = req.query['shirt[color]'];
res.json({
shoe: { color: shoeColor },
shirt: { color: shirtColor }
});
});
Filtering with Arrays Example:
app.get('/apples', (req, res) => {
// URL: /apples?filterBy=Empire&filterBy=Granny%20Smith
// req.query: { filterBy: ['Empire', 'Granny Smith'] }
const apples = [
{ type: 'Empire', price: '$1.20', quantity: 10 },
{ type: 'Granny Smith', price: '$0.85', quantity: 8 },
{ type: 'Gala', price: '$0.98', quantity: 4 }
];
const { filterBy = [] } = req.query;
const filteredApples = apples.filter(apple =>
filterBy.includes(apple.type)
);
res.json(filteredApples);
});
According to Mastering JS, when a query parameter appears multiple times, Express automatically groups the values into an array, making it easy to work with multiple selections.
Query Parser Configuration Options
Express.js allows you to configure how query strings are parsed, giving you flexibility in handling different parameter formats.
Configuration Example:
const express = require('express');
const app = express();
// Configure query parser
app.set('query parser', 'simple'); // Default: 'extended'
app.set('query parser fn', (str) => {
// Custom query parser function
return require('qs').parse(str);
});
app.get('/configured', (req, res) => {
// Custom parsing behavior
res.json(req.query);
});
Parser Types:
'simple': Parses query string into simple key-value pairs'extended': Allows for nested objects and arrays (default)
Complete Practical Examples
Here are some complete examples showing how to work with query parameters in real-world scenarios.
Search Application Example:
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
const { q, page = '1', limit = '10', sort = 'relevance' } = req.query;
// Validate input
if (!q) {
return res.status(400).json({ error: 'Search query is required' });
}
// Convert to numbers
const pageNum = parseInt(page, 10);
const limitNum = parseInt(limit, 10);
// Business logic
const searchResults = [
{ id: 1, title: 'Express.js Tutorial', relevance: 0.95 },
{ id: 2, title: 'Node.js Best Practices', relevance: 0.88 },
{ id: 3, title: 'Web Development with Express', relevance: 0.82 }
];
// Sort results
const sortedResults = [...searchResults].sort((a, b) => {
if (sort === 'relevance') {
return b.relevance - a.relevance;
}
return a.title.localeCompare(b.title);
});
// Paginate results
const startIndex = (pageNum - 1) * limitNum;
const endIndex = startIndex + limitNum;
const paginatedResults = sortedResults.slice(startIndex, endIndex);
res.json({
query: q,
page: pageNum,
limit: limitNum,
total: sortedResults.length,
results: paginatedResults
});
});
app.listen(3000, () => {
console.log('Search app running on port 3000');
});
API Filtering and Sorting Example:
app.get('/api/products', (req, res) => {
const {
category,
minPrice,
maxPrice,
inStock,
sortBy = 'name',
sortOrder = 'asc'
} = req.query;
// Filter products
let filteredProducts = allProducts.filter(product => {
if (category && product.category !== category) return false;
if (minPrice && product.price < parseFloat(minPrice)) return false;
if (maxPrice && product.price > parseFloat(maxPrice)) return false;
if (inStock && product.inStock !== (inStock === 'true')) return false;
return true;
});
// Sort products
filteredProducts.sort((a, b) => {
const modifier = sortOrder === 'desc' ? -1 : 1;
if (sortBy === 'price') {
return (a.price - b.price) * modifier;
}
return a[sortBy].localeCompare(b[sortBy]) * modifier;
});
res.json({
total: filteredProducts.length,
products: filteredProducts.slice(0, 20) // Limit to first 20 results
});
});
Sources
- Stack Overflow - How to get GET (query string) variables in Express.js on Node.js?
- Stack Abuse - Get Query Strings and Parameters in Express.js
- Better Stack Community - How to get
GETvariables in Express.js on Node.js? - Tutorialspoint - Getting Query String Variables in Express.js
- Flavio Copes - Retrieve the GET query string parameters using Express
- Sentry - Access GET parameters in Express on Node.js
- Mastering JS - Query Parameters in Express
- GeeksforGeeks - Difference Between req.query and req.params in Express
- DEV Community - Express: req.params, req.query and req.body
- Derek Hassan - How to Pass an Array as a Query String to Express
Conclusion
Accessing query string parameters in Express.js is straightforward using the req.query object, which provides a powerful and flexible way to work with GET variables. The key takeaways include:
- Use
req.queryto access all query string parameters as an object - Express automatically handles multiple values by converting them to arrays
- Nested parameters work using bracket notation like
param[key]=value - You can configure the query parser for different parsing behaviors
- Always validate and sanitize query parameters before using them in your application logic
By following these practices, you can effectively handle query parameters in your Express.js applications, providing users with intuitive URL-based filtering, searching, and data retrieval capabilities similar to what you’d find in traditional PHP applications.