How to Get URL Parameters in Node.js

nodejs
Published on October 15, 2018

URL parameters can be in read in Node.js by importing the built-in url module, and using the URL and URLSearchParams objects present in it.

const url = require('url');

// new URL object
const current_url = new URL('http://usefulangle.com/preview?id=123&type=article');

// get access to URLSearchParams object
const search_params = current_url.searchParams;

// get url parameters
const id = search_params.get('id');
const type = search_params.get('type');

// "123"
console.log(id);

// "article"
console.log(type);

Getting Parameter Value By Name

The get() method of URLSearchParams object gets the value of the given parameter.

const url = require('url');
    
const current_url = new URL('http://usefulangle.com/preview?id=123&type=article');
const search_params = current_url.searchParams;

const id = search_params.get('id');

// "123"
console.log(id);

Getting Values of Multi-Valued Parameter

The getAll() method of URLSearchParams object returns an array of values of the given parameter.

const url = require('url');

const current_url = new URL('http://usefulangle.com/preview?tags=javascript&tags=pdfjs');
const search_params = current_url.searchParams;

const tags = search_params.getAll('tags');

// [ "javascript", "pdfjs" ]
console.log(tags);

Checking If Parameter Present

The has() method of URLSearchParams object checks whether given parameter exists in the url.

const url = require('url');

const current_url = new URL('http://usefulangle.com/preview?id=123&type=article');
const search_params = current_url.searchParams;

// true
if(search_params.has('id')) {
    // 
}

// false
if(search_params.has('name')) {
    // 
}
Related Tutorials
Routing in Node.js (without framework)
Getting POST Parameters in Node.js
Comments
Loading Comments