Get URL Parameters in Node.js
Last updated: February 21, 2023.
Data can be added to the end of a URL in query string format, like this:
https://some-url.com/page?key1=vaue1&key2=value2&key3=value3
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
res.end();
});
app.listen(3000);
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(
req.url,
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
}
res.end();
});
app.listen(3000);
Related post
- How to create and decode a query string in JavaScript
- Create a HTTP Server in Node.js
- Serve Static Files in Node.js with Express
- Build a REST API with Node.js and Express
- Web scraping in NodeJS with Puppeteer