Skip to main content

Command Palette

Search for a command to run...

Path Parameters vs. Query Parameters in Express.js

Updated
2 min read

When building APIs, we constantly need to read dynamic data sent through URLs. A client might want to view a specific user profile or search for all users who live in a certain city.

Express.js gives us two distinct ways to capture this URL data: Path Parameters and Query Parameters.

1. Path Parameters: The Identifiers

Path parameters are variables embedded directly into the URL path. We use them when we need to identify a specific, unique resource.

If the data is absolutely required to point to the correct item in our database, it should be a path parameter.

The Syntax:
In Express, we define a path parameter by placing a colon : before a word in our route. We then access that value using the req.params object.

// A client visits: /users/104

app.get('/users/:id', (req, res) => {
    // We capture the dynamic 'id' from the URL path
    const userId = req.params.id; 
    
    res.json({ message: `Fetching specific user with ID: ${userId}` });
});

2. Query Parameters: The Modifiers

Query parameters are key-value pairs appended to the very end of a URL, separated from the main path by a question mark ?. We use them to filter, sort, or paginate a list of resources.

Unlike path parameters, query parameters are generally optional. If we remove them from the URL, the route should still work (it would just return an unfiltered list).

The Syntax:
We do not define query parameters in our Express route path. Express automatically parses anything after the ? and attaches it to the req.query object.

// A client visits: /users?role=admin&sort=asc

app.get('/users', (req, res) => {
    // We capture the optional filters from the URL query string
    const targetRole = req.query.role; 
    const sortOrder = req.query.sort;  
    
    res.json({ 
        message: `Fetching a list of users`, 
        filtersApplied: { role: targetRole, sort: sortOrder } 
    });
});

The Golden Rule

When deciding which one to use, we can follow this simple rule:

  • Does the variable define exactly what resource we are looking for? Use a Path Parameter (/users/123).

  • Does the variable just change how a list of resources is displayed or filtered? Use a Query Parameter (/users?status=active).

By adhering to this standard, our APIs remain predictable and easy for other developers to consume.