Handling Query Parameters in Express.js

🚀 Introduction

Query parameters are key-value pairs appended to the end of a URL after a question mark (?). They allow clients to send additional information to the server without changing the URL path. In Express.js, query parameters are easily accessed using the req.query object.

Information

Query parameters are commonly used for searching, filtering, sorting, pagination, and passing optional data to the server.

📋 Prerequisites

  • Node.js installed.
  • Express.js installed.
  • A basic Express server created.
  • Basic understanding of HTTP requests and URLs.

❓ What Are Query Parameters?

Query parameters appear after the URL path and consist of one or more key-value pairs. Multiple parameters are separated using the & character.

URLQuery Parameters
/search?keyword=laptopkeyword = laptop
/users?page=2page = 2
/products?category=electronics&sort=pricecategory = electronics, sort = price

🌐 URL Structure

URL
Path
Query Parameters
/products
category=electronics
sort=price
page=1

📝 Accessing Query Parameters

Express automatically parses query parameters and stores them in the req.query object.

Accessing Query Parameters

const express = require('express');

const app = express();

app.get('/search', (req, res) => {
  const keyword = req.query.keyword;

  res.send(`Searching for: ${keyword}`);
});

app.listen(3000);

Visiting http://localhost:3000/search?keyword=laptop produces the following response:

Response

Searching for: laptop

📌 Multiple Query Parameters

Reading Multiple Parameters

app.get('/products', (req, res) => {
  const category = req.query.category;
  const sort = req.query.sort;
  const page = req.query.page;

  res.json({
    category,
    sort,
    page
  });
});

Example request:
/products?category=electronics&sort=price&page=2

📤 Example Response

JSON Response

{
  "category": "electronics",
  "sort": "price",
  "page": "2"
}

Tip

Values in req.query are received as strings. Convert them to numbers or other data types when necessary.

đŸ”ĸ Converting Query Parameters

Convert to Number

app.get('/users', (req, res) => {
  const page = Number(req.query.page) || 1;

  res.send(`Current Page: ${page}`);
});

🔍 Providing Default Values

Default Query Parameter

app.get('/search', (req, res) => {
  const keyword = req.query.keyword || 'all';

  res.send(`Searching for: ${keyword}`);
});

If the client visits /search without providing a keyword, the response will be:

Response

Searching for: all

📊 Common Use Cases

Use CaseExample URL
Search/search?keyword=phone
Pagination/users?page=3
Sorting/products?sort=price
Filtering/products?category=laptops
Language Selection/docs?lang=en

🔄 Request Lifecycle with Query Parameters

📌 Query Parameters vs Route Parameters

FeatureQuery ParametersRoute Parameters
LocationAfter ? in the URLPart of the URL path
Access Methodreq.queryreq.params
PurposeFiltering, searching, sorting, paginationIdentifying a specific resource
Example/products?category=books/products/101

💡 Best Practices

  • Use query parameters for optional request data.
  • Use route parameters to identify specific resources.
  • Validate and sanitize query parameter values before using them.
  • Provide sensible default values for optional parameters.
  • Convert numeric query parameters using Number() or parseInt() when appropriate.
  • Use descriptive parameter names to improve API readability.

Warning

Never assume query parameters are valid. Always validate user input to prevent unexpected behavior and improve application security.

📚 Learn More

Explore the official Express.js documentation for handling requests:
â€ĸ Express.js Request - req.query
â€ĸ Express.js Official Documentation

📝 Summary

Summary

Query parameters provide a flexible way to send optional information from the client to the server. Express.js automatically parses these parameters into the req.query object, making it simple to implement features such as searching, filtering, sorting, and pagination. Proper validation and sensible defaults help create reliable and user-friendly applications.