Skip to main content

Command Palette

Search for a command to run...

URL Parameters vs Query Strings in Express.js

Updated
5 min read

When building web applications using Express.js on top of Node.js, handling user input through URLs is a fundamental concept. Two of the most common ways to pass data in a URL are:

  • URL Parameters (Route Parameters)

  • Query Strings

At first glance, they might seem similar—but they serve different purposes and are used in different scenarios. Understanding the difference is crucial for designing clean, scalable, and RESTful APIs.

In this detailed blog, we’ll break down both concepts with examples, compare them, and explore best practices for real-world applications.

Understanding URLs

Before diving deeper, let’s understand the structure of a URL:

http://example.com/users/123?sort=asc&limit=10

Parts:

  • /users/123 → URL parameter

  • ?sort=asc&limit=10 → Query string

What are URL Parameters?

Definition

URL parameters (also called route parameters) are dynamic values embedded directly in the URL path.

Example:

/users/123

Here:

  • 123 is a URL parameter representing a specific user

How to Use URL Parameters in Express

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

app.get("/users/:id", (req, res) => {
  res.send(`User ID is ${req.params.id}`);
});

app.listen(3000);

Accessing Parameters:

req.params.id

Example Request

http://localhost:3000/users/101

Response:

User ID is 101

Multiple Parameters

app.get("/users/:userId/posts/:postId", (req, res) => {
  res.send(`User: \({req.params.userId}, Post: \){req.params.postId}`);
});

Use Cases for URL Parameters

  • Fetching a specific resource

  • RESTful APIs

  • Identifying unique entities

Examples:

  • /products/45

  • /orders/789

  • /students/101/results


What are Query Strings?

Definition

Query strings are key-value pairs appended to the end of a URL after a ?.

Example:

/products?category=electronics&price=1000

How to Use Query Strings in Express

app.get("/products", (req, res) => {
  const category = req.query.category;
  const price = req.query.price;

  res.send(`Category: \({category}, Price: \){price}`);
});

Example Request

http://localhost:3000/products?category=books&price=500

Response:

Category: books, Price: 500

Multiple Query Parameters

app.get("/search", (req, res) => {
  res.json(req.query);
});

Request:

/search?name=Kanishka&age=21&city=Meerut

Use Cases for Query Strings

  • Filtering data

  • Sorting results

  • Pagination

  • Searching

Examples:

  • /products?sort=price

  • /users?page=2

  • /movies?genre=comedy

URL Parameters vs Query Strings

Let’s compare both:

Feature URL Parameters Query Strings
Position in URL Inside path After ?
Purpose Identify resource Filter/modify data
Required Usually required Usually optional
Example /users/123 /users?age=21
Access Method req.params req.query
RESTful Usage Strongly recommended Optional

Key Differences Explained

1. Resource vs Filter

  • URL Parameter → Which resource?

  • Query String → How to modify results?

Example:

/users/123        → specific user
/users?age=21     → users filtered by age

2. Mandatory vs Optional

  • URL params are usually required

  • Query params are optional


3. Readability

/products/10       → cleaner
/products?id=10    → less RESTful

Combining Both

You can use both together:

app.get("/users/:id", (req, res) => {
  const id = req.params.id;
  const showPosts = req.query.posts;

  res.send(`User \({id}, Show posts: \){showPosts}`);
});

Request:

/users/101?posts=true

Real-World API Examples

E-commerce API

/products/45
/products?category=clothing&sort=price

Social Media API

/users/101
/posts?tag=travel&limit=10

Movie App

/movies/500
/movies?genre=action&year=2024

Validation & Error Handling

Validate URL Parameters

app.get("/users/:id", (req, res) => {
  const id = parseInt(req.params.id);

  if (isNaN(id)) {
    return res.status(400).send("Invalid ID");
  }

  res.send(`User ID: ${id}`);
});

Validate Query Strings

app.get("/products", (req, res) => {
  const limit = parseInt(req.query.limit) || 10;

  res.send(`Limit: ${limit}`);
});

Use Validation Libraries

  • express-validator

  • Joi


Common Mistakes

1. Using Query Instead of Params for IDs

/users?id=101   ❌

Better:

/users/101      ✅

2. Overloading URL Parameters

/products/10/cheap/red   ❌

Better:

/products/10?price=cheap&color=red   ✅

3. Not Handling Missing Query Params

Always set defaults.


Best Practices

1. Follow RESTful Design

  • Use URL params for resource IDs

  • Use query strings for filters


2. Keep URLs Clean

Avoid unnecessary complexity


3. Use Meaningful Names

/users/:userId   ✅

4. Limit Query Parameters

Too many parameters = confusion


5. Secure Input

Always validate and sanitize


Advanced Concepts

Pagination

/products?page=2&limit=10

Searching

/users?name=kanishka

Sorting

/products?sort=price&order=asc

Testing APIs

Use tools like:

  • Postman

  • Insomnia


Real-Life Analogy

Think of a library:

  • 📘 /books/101 → specific book (URL param)

  • 🔍 /books?author=xyz → search/filter (query string)


Conclusion

Both URL parameters and query strings are essential tools in building APIs with Express.js.

Key Takeaways:

  • URL Parameters

    • Used to identify specific resources

    • Required and RESTful

  • Query Strings

    • Used for filtering, sorting, pagination

    • Optional and flexible

Using them correctly will:

  • Improve API design

  • Enhance readability

  • Make your application scalable


Final Thoughts

Mastering URL handling in Node.js is a key step toward becoming a professional backend developer.

When you design APIs:

  • Think clearly about what vs how

  • Keep endpoints clean and logical