Get Query Strings and Parameters in Express.js

Introduction

We'll be going over how to extract information from a URL in Express.js. Specifically, how do we extract information from a query string and how do we extract information from the URL path parameters?

In this article, I assume you have some experience with Node.js and creating Express.js servers (or at least simple ones). The rest we'll explain throughout the article.

Extracting Query Parameters

Before we start, it'd be helpful to first understand what exactly a query string/parameter is, and then we'll talk about how we can work with them.

So, what is a query parameter?

In simple terms, a query string is the part of a URL (Uniform Resource Locator) after the question mark (?). It is meant to send small amounts of information to the server via the URL. This information is usually used as parameters to query a database, or maybe to filter results. It's really up to you what they're used for.

Here is an example of a URL with query strings attached:

https://stackabuse.com/?page=2&limit=3

The query parameters are the actual key-value pairs like page and limit with values of 2 and 3, respectively.

Now, let's move on to the first main purpose of this article - how to extract these from our Express request object.

This is a pretty common use-case in Express, and any HTTP server, so hopefully the examples and explanations I show here are clear.

Now, taking the same example from above:

https://stackabuse.com/?page=2&limit=3

We'd like to extract both the page and limit parameters so we know which articles to return to the page that the user requested. While query parameters are typically used in GET requests, it's still possible to see them in POST and DELETE requests, among others.

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

Let's take a look at an example of us getting query parameters in a route:

const express = require('express');
const bodyParser = require('body-parser');
const url = require('url');
const querystring = require('querystring');
const Article = require('./models').Article;

let app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Function to handle the root path
app.get('/', async function(req, res) {

    // Access the provided 'page' and 'limt' query parameters
    let page = req.query.page;
    let limit = req.query.limit;

    let articles = await Article.findAll().paginate({page: page, limit: limit}).exec();

    // Return the articles to the rendering engine
    res.render('index', {
        articles: articles
    });
});

let server = app.listen(8080, function() {
    console.log('Server is listening on port 8080')
});

In the example above, we assume the page and limit parameters always exist. If neither of these parameters are given in the URL, we'd receive undefined for both page and limit instead.

Extract Query Parameters Without Express

As a quick bonus, I wanted to show you how to do the actual parsing on your own in case you need to extract information from a URL that isn't using Express, or any other web framework. It's fairly common to create a dead-simple server using the http module, so this is good to know.

Lucky for you, Node.js already provides some great core libraries that have this functionality built in, so it is just a matter of require-ing the module and calling a few lines of code.

Here is an example using the querystring and url packages.

const url = require('url');
const querystring = require('querystring');

let rawUrl = 'https://stackabuse.com/?page=2&limit=3';

let parsedUrl = url.parse(rawUrl);
let parsedQs = querystring.parse(parsedUrl.query);

// parsedQs = { page: '2', limit: '3' }

You can see in this code that we require two parsing steps to get the results we want.

Let's break this down a bit further and show what exactly is going on at each step. After calling url.parse(rawUrl) on our URL, this is what is returned to us:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

{
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'stackabuse.com',
    port: null,
    hostname: 'stackabuse.com',
    hash: null,
    search: '?page=2&limit=3',
    query: 'page=2&limit=3',
    pathname: '/',
    path: '/?page=2&limit=3',
    href: 'https://stackabuse.com/?page=2&limit=3'
}

Okay, we're a bit closer getting the data we need. But it needs to be broken down one more time. We can do this using the querystring package to parse the actual query string. For example:

let parsedQs = querystring.parse(parsedUrl.query);

And finally, our parsedQs object contains the following:

{
    page: '2',
    limit: '3'
}

Extracting Route Parameters

In any web application another common way to structure your URLs is to place information within the actual URL path, which are simply called route parameters in Express. We can use these to structure web pages by information/data, which are especially useful in REST APIs.

Extracting these route parameters is similar to the query parameters. All we do is take the req object and retrieve our params from the params object. Pretty simple, right?

Let's take a look at an example of doing this in our Express route:

// Route to return all articles with a given tag
app.get('/tag/:id', async function(req, res) {
    
    // Retrieve the tag from our URL path
    var id = req.params.id;

    let articles = await Article.findAll({tag: id}).exec();

    res.render('tag', {
        articles: articles
    });
});

First thing to notice is that we tell Express that our route is /tag/:id, where :id is a placeholder for anything. It could be a string or a number. So whatever is passed in that part of the path is set as the id parameter.

If we were to navigate to the URL https://stackabuse.com/tag/node then id would be node, and we'd get a bunch of articles that have the node tag on them. And req.params in this case would be {id: 'node'}, just like the query object.

As you can see, we again just take our parameter directly from an object contained within the request object.

Conclusion

In this article I presented ways to extract both the query string parameters and route path parameters from a URL in the Express web framework. Here is a quick recap of how to extract the parameters we talked about:

  • req.query: directly access the parsed query string parameters
  • req.params: directly access the parsed route parameters from the path

While the actual act of retrieving this data is very simple, understanding where this info comes from and what it is can be confusing for some beginners. Hopefully this article cleared some things up for you. Feel free to let us know in the comments if there is anything that is unclear.

Last Updated: July 12th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms