Sling Academy
Home/Node.js/How to Get Query String Values in Express.js

How to Get Query String Values in Express.js

Last updated: December 28, 2023

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.

Next Article: How to Extract Headers in Express.js

Previous Article: Authentication and Authorization in Express.js with JWT

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates