0
0
NodejsHow-ToBeginner · 3 min read

How to Get Query String from URL in Node.js Easily

In Node.js, you can get the query string from a URL using the built-in URL class by creating a new URL object and accessing its searchParams property. This lets you easily read query parameters with methods like get() or entries().
📐

Syntax

Use the URL class to parse a URL string. Then access searchParams to work with the query string.

  • new URL(input): Creates a URL object from a string.
  • url.searchParams: Provides access to query parameters.
  • searchParams.get(name): Gets the value of a specific query parameter.
javascript
const url = new URL('https://example.com/page?name=alice&age=25');
const name = url.searchParams.get('name');
const age = url.searchParams.get('age');
💻

Example

This example shows how to extract query parameters from a URL string and print them.

javascript
import { URL } from 'url';

const urlString = 'https://example.com/page?name=alice&age=25';
const url = new URL(urlString);

console.log('Name:', url.searchParams.get('name'));
console.log('Age:', url.searchParams.get('age'));

// Loop through all query parameters
for (const [key, value] of url.searchParams.entries()) {
  console.log(`${key}: ${value}`);
}
Output
Name: alice Age: 25 name: alice age: 25
⚠️

Common Pitfalls

One common mistake is trying to parse URLs without specifying a base when the URL is relative, which causes errors. Always provide a full URL or a base URL when using the URL constructor.

Another mistake is trying to parse the query string manually by splitting strings, which is error-prone and unnecessary.

javascript
import { URL } from 'url';

// Wrong: relative URL without base
// const url = new URL('/page?name=alice'); // Throws error

// Right: provide base URL
const url = new URL('/page?name=alice', 'https://example.com');
console.log(url.searchParams.get('name')); // alice
Output
alice
📊

Quick Reference

MethodDescription
new URL(input)Creates a URL object from a string
url.searchParams.get(name)Gets the value of a query parameter
url.searchParams.has(name)Checks if a query parameter exists
url.searchParams.entries()Returns all query parameters as [key, value] pairs
url.searchParams.append(name, value)Adds a new query parameter

Key Takeaways

Use the built-in URL class to parse URLs and access query strings safely.
Always provide a full URL or a base URL when creating a URL object to avoid errors.
Use url.searchParams.get('param') to get specific query parameter values.
Avoid manual string splitting to parse query strings; use URLSearchParams instead.
Loop through all query parameters with url.searchParams.entries() for full access.