Get URL Parameters in Node.js

OpenJavaScript 0

Last updated: February 21, 2023.

Data can be added to the end of a URL in query string format, like this:

With Express

If using the Express framework in Node.js, you can extract URL parameters via the query property on the incoming request:

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

app.get('/page', function(req, res) {

    // Get all parameters as object:
    console.log(req.query); // { key1: 'value1', key2: 'value2', key3: 'value3' }

    // Get single parameter:
    console.log(req.query.key1); // value1




Vanilla Node.js solution

Using pure Node.js, you can use the in-built url module to parse parameters on the URL and return them in JS object format:

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

const app = http.createServer(function(req, res) {

    // Get information object about request URL:
    const parsedURL = url.parse(
        true // 'true' sets parameters to be returned in object format

    // Handle request to '/page' route:
    if (parsedURL.pathname === '/page') {

        // Get all parameters:
        console.log(parsedURL.query); // { key1: 'value1', key2: 'value2', key3: 'value3' }
        // Get key1 parameter:
        console.log(parsedURL.query.key1); // value1





Related post