0
0
Expressframework~5 mins

Query string parsing in Express

Choose your learning style9 modes available
Introduction

Query string parsing helps you get information from the URL after the question mark. This lets your app understand what the user wants.

When you want to read filters or search terms from a URL like /products?category=books
When you need to get page numbers or limits for showing lists, like /items?page=2&limit=10
When you want to customize responses based on user choices sent in the URL
When handling form submissions sent via GET method
When building APIs that accept parameters in the URL query
Syntax
Express
app.get('/path', (req, res) => {
  const value = req.query.key;
  // use value
  res.send(`Value is ${value}`);
});

req.query is an object containing all query parameters as strings.

If a parameter is missing, its value will be undefined.

Examples
Reads the term parameter from the query string like /search?term=books
Express
app.get('/search', (req, res) => {
  const term = req.query.term;
  res.send(`Search term: ${term}`);
});
Uses a default value if page is not provided in the URL.
Express
app.get('/items', (req, res) => {
  const page = req.query.page || 1;
  res.send(`Page number: ${page}`);
});
Extracts multiple query parameters at once using object destructuring.
Express
app.get('/filter', (req, res) => {
  const { category, sort } = req.query;
  res.send(`Category: ${category}, Sort: ${sort}`);
});
Sample Program

This Express app listens on port 3000. When you visit /products?category=books&page=2, it reads the query parameters and shows them in the response.

Express
import express from 'express';

const app = express();
const port = 3000;

app.get('/products', (req, res) => {
  const category = req.query.category || 'all';
  const page = Number(req.query.page) || 1;
  res.send(`Showing products in category: ${category}, page: ${page}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Query parameters are always strings. Convert them to numbers or booleans if needed.

Use default values to avoid errors when parameters are missing.

Express automatically parses the query string into req.query.

Summary

Query string parsing lets you read extra info from URLs.

Use req.query in Express to get query parameters as an object.

Always handle missing or wrong types by setting defaults or converting values.