HVRDHVRD
JavaScript

Query Parameters

Comprehensive guide to understanding, using, and handling query parameters in URLs for web applications and Express servers.

Query Parameters

Query parameters are key-value pairs appended to a URL, commonly used to send additional data to the server or control resource filtering, sorting, pagination, and more.

A typical URL with query parameters looks like this:

https://example.com/products?category=books&sort=price_asc&page=2
  • category=books, sort=price_asc, and page=2 are query parameters.

Structure of Query Parameters

  • They start after the ? in a URL.
  • Multiple parameters are separated by &.
  • Each key and value is connected by =.

Example:

https://example.com/search?q=laptop&brand=apple&limit=10
  • q=laptop
  • brand=apple
  • limit=10

Why Use Query Parameters?

  • Filter or sort results.
  • Pass pagination info.
  • Send non-sensitive data without a request body.
  • Shareable URLs that represent a specific view.

Accessing Query Parameters in JavaScript

Using URLSearchParams

const url = 'https://example.com/products?category=books&sort=price_asc&page=2';
const urlObj = new URL(url);

const params = new URLSearchParams(urlObj.search);

console.log(params.get('category')); // "books"
console.log(params.get('sort'));     // "price_asc"
console.log(params.get('page'));     // "2"

Iterating All Parameters

for (const [key, value] of params.entries()) {
  console.log(`${key}: ${value}`);
}

Modifying Query Parameters

Adding or Updating Parameters

const params = new URLSearchParams();
params.set('category', 'electronics');
params.set('limit', '20');

const queryString = params.toString();
console.log(queryString);
// Output: "category=electronics&limit=20"

You can append parameters as well:

params.append('sort', 'price_desc');

Removing Query Parameters

params.delete('limit');

console.log(params.toString());
// Output: "category=electronics&sort=price_desc"

Working with Window Location

You can read and modify the current page URL.

Reading Query Parameters

const params = new URLSearchParams(window.location.search);
const searchTerm = params.get('q');
console.log(searchTerm);

Updating Query Parameters Without Reload

const params = new URLSearchParams(window.location.search);
params.set('page', '3');
const newUrl = `${window.location.pathname}?${params.toString()}`;
window.history.pushState({}, '', newUrl);

Encoding Considerations

Query parameters must be URL-encoded to handle special characters.

const params = new URLSearchParams();
params.set('search', 'smart phone & accessories');
console.log(params.toString());
// Output: "search=smart+phone+%26+accessories"

Use encodeURIComponent() if constructing query strings manually.


Common Use Cases

Pagination

https://example.com/articles?page=4&limit=10
  • Controls which page of data and how many items per page to return.

Filtering

https://example.com/products?category=electronics&brand=sony
  • Return only products matching the filter criteria.

Sorting

https://example.com/products?sort=price_desc
  • Define sort order of data.

Using Query Parameters in Express Server

In an Express server, query parameters are accessible via req.query.

Example Route Handling

const express = require('express');
const app = express();

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

  console.log('Category:', category);
  console.log('Sort:', sort);
  console.log('Page:', page);
  console.log('Limit:', limit);

  res.json({
    category,
    sort,
    page,
    limit,
    message: 'Fetched filtered products successfully'
  });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Using Route-Based Parameters in Express Server

Route parameters are part of the URL path and are accessible via req.params.

Example Route Handling

const express = require('express');
const app = express();

// Route with a dynamic parameter
app.get('/products/:id', (req, res) => {
  const productId = req.params.id;

  console.log('Product ID:', productId);

  // Example logic: fetch product by ID from database
  res.json({
    id: productId,
    name: 'Sample Product',
    message: 'Fetched product by ID'
  });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Example Request

GET /products/123
  • req.params.id will be '123'.

This approach is useful when the parameter is required for resource identification.


Best Practices

  • Always encode query parameters.
  • Validate user-supplied parameters on the server.
  • Do not pass sensitive data via query parameters.
  • Use defaults for missing parameters.
  • For complex filters, consider structured objects or POST requests.