How to get `GET` variables in Express.js on Node.js?

Better Stack Team
Updated on March 11, 2024

In Express.js, you can access GET (query string) variables using the req.query object. The req.query object contains key-value pairs of the query string parameters in a GET request. Here's an example:

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

// Define a route with a query string parameter
app.get('/example', (req, res) => {
  // Access query string variables using req.query
  const param1 = req.query.param1;
  const param2 = req.query.param2;

  // Do something with the parameters
  res.send(`Received parameters: param1=${param1}, param2=${param2}`);
});

// Start the server
const port = 3000;
app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

In this example:

  • The route /example is defined to handle GET requests.
  • Inside the route handler function, req.query is used to access the query string parameters.
  • param1 and param2 represent the names of the query string parameters. You should replace them with the actual parameter names you expect in your application.

When a request is made to a URL like http://localhost:3000/example?param1=value1&param2=value2, the values of param1 and param2 will be accessible in the route handler through req.query.

For a more dynamic approach, you can also destructure the properties directly from req.query:

 
app.get('/example', (req, res) => {
  const { param1, param2 } = req.query;

  res.send(`Received parameters: param1=${param1}, param2=${param2}`);
});

This way, you directly extract the properties you need from req.query into variables.