How to Get a URL Parameter in Express

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Working with URL parameters is a common task for web developers. URL parameters, often known as query strings or path variables, are used to send small amounts of data from the client to the server. Express, a flexible Node.js web application framework, simplifies the process of handling these parameters. This tutorial covers multiple methods to retrieve URL parameters using Express. Whether you’re a beginner or an experienced developer, you’ll find valuable insights into how URL parameters work in Express.

Getting Started with URL Parameters

To follow along, ensure you have Node.js and Express installed. If not, you can install them via the Node.js website or through your package manager of choice. You will also need to set up a basic Express application.

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Retrieving Route Parameters

Route parameters are part of the URL path. Let’s look at how to extract these using Express:

app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`User ID: ${userId}`);
});

In this example, :userId is a route parameter. When a GET request is made to /users/123, req.params.userId will be '123'.

Handling Multiple Route Parameters

Express also allows handling multiple route parameters within a single route.

app.get('/books/:bookId/pages/:pageNumber', (req, res) => {
  const { bookId, pageNumber } = req.params;
  res.send(`Book ID: ${bookId}, Page Number: ${pageNumber}`);
});

If a request is made to /books/42/pages/7, req.params will be { bookId: '42', pageNumber: '7' }.

Query String Parameters

Query strings are another way to pass parameters. They are appended to the URL after a ‘?’ and separated by ‘&’. To access these in Express:

app.get('/search', (req, res) => {
  const { q } = req.query;
  res.send(`Search query: ${q}`);
});

A request to /search?q=express would result in req.query.q being 'express'.

Combining Route and Query String Parameters

It’s possible to mix both types of parameters in a single request.

app.get('/events/:eventId', (req, res) => {
  const { eventId } = req.params;
  const { sortBy } = req.query;
  res.send(`Event ID: ${eventId}, Sort By: ${sortBy}`);
});

So, a request to /events/100?sortBy=date allows you to access both the event ID and the query string for sorting.

Advanced Parameter Handling

For more complex scenarios, such as optional parameters or pattern matching, Express provides additional tools.

Optional Parameters

app.get('/users/:userId/books/:bookId?', (req, res) => {
  const { userId, bookId } = req.params;
  let response = `User ID: ${userId}`;
  if (bookId) response += `, Book ID: ${bookId}`;
  res.send(response);
});

Here, :bookId is optional. It matches both /users/123/books/ and /users/123/books/456.

Parameter Patterns

You can also use regular expressions to constrain the values that can be passed as parameters:

app.get('/users/:userId(\d+)', (req, res) => {
  res.send(`User ID is a number: ${req.params.userId}`);
});

This route will only match if :userId is a number.

Conclusion

We’ve covered the basics of capturing URL parameters in Express, handling multiple parameters, accessing query strings, and more advanced routing patterns. These fundamental concepts are crucial when developing APIs and web applications with Node.js and Express. With this knowledge, you can handle client data passed through URLs effectively, bolstering the interactivity and flexibility of your applications.

For more complex scenarios, Express’s robust routing API offers further capabilities, including custom handling of parameters, advanced pattern matching, and more. Take the time to explore the Express documentation to deepen your understanding and skills with these routing features.