How to Get Query String Values in Express.js

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

Overview

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. One common task when working with web applications is retrieving query string values from the URL. This tutorial will guide you through different ways of accessing query string values in an Express.js application, from the simplest methods to more advanced use-cases.

Accessing Query Strings

When a user makes a GET request to your server with a URL like ‘http://yourapp.com/page?name=John&age=30’, the server receives the query string ‘?name=John&age=30’. Express.js makes it very straightforward to access these values.

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

app.get('/page', (req, res) => {
    let name = req.query.name;
    let age = req.query.age;
    res.send(`Name is ${name}, and age is ${age}`);
});

app.listen(3000);

This basic example demonstrates how you can access the query parameters ‘name’ and ‘age’ using req.query object.

Handling Multiple Values for a Single Query Parameter

In some cases, a query parameter might have multiple values. Express.js automatically parses these into an array.

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

For a URL like ‘http://yourapp.com/search?tags=express&tags=node’, ‘tags’ will be parsed into an array [‘express’, ‘node’].

Default Query Parameters

It’s a good practice to provide default values for query parameters to avoid issues with undefined values.

app.get('/book', (req, res) => {
    let page = req.query.page || 1;
    res.send(`Currently on page ${page}`);
});

This code sets a default value of ‘1’ for the ‘page’ parameter if it is not provided in the query string.

Advanced Parsing Options

Express.js leverages the ‘qs’ library to parse query strings. You can customize query string parsing behavior by modifying the ‘query parser’ configuration.

const qs = require('qs');
app.set('query parser', (str) => {
    return qs.parse(str, { comma: true });
});

This example demonstrates how to use the ‘qs’ library to have Express.js parse comma-separated values in query strings.

Security Considerations

When working with query strings, always consider security implications. For example, ensure you validate and sanitize query parameters to prevent command injection or other malicious activities.

Conclusion

In this tutorial, you’ve learned how to efficiently retrieve query string values in an Express.js application. We’ve explored several techniques ranging from simple retrieval to more complex parsing strategies and security considerations to help you comfortably handle query strings in your web applications.

Remember that when developing Express.js applications, understanding how to work with query string values is crucial for tasks such as filtering data, configuring application behavior, and much more. With the examples provided, you now have the resources to implement these features in your own projects.