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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github