Course contentsShow
← JavaScript
Lesson 2263 of 2,72347. Networking PrimitivesFree lesson

Query Parameters in URLs

Building URLs with query strings for GET requests using URLSearchParams.

Query Parameters in URLs

You'll learn how to construct URLs with query strings for GET requests using JavaScript's built-in URLSearchParams API.

What Are Query Parameters?

Query parameters are key-value pairs appended to a URL after a ? symbol, used to send data to a server in GET requests. Think of them like filling out a form in the URL itself: https://api.example.com/search?term=javascript&limit=10.

While you could manually build these strings with string concatenation, that's error-prone and doesn't handle special characters properly. JavaScript provides URLSearchParams to construct query strings safely and cleanly.

Building URLs with URLSearchParams

The URLSearchParams constructor creates an object that manages query parameters:

const params = new URLSearchParams();
params.append('query', 'fetch api');
params.append('page', '2');
params.append('filter', 'recent');

console.log(params.toString()); 
// "query=fetch+api&page=2&filter=recent"

You can then combine this with your base URL:

const baseUrl = 'https://api.example.com/search';
const url = `${baseUrl}?${params.toString()}`;

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

URLSearchParams automatically handles URL encoding (spaces become +, special characters are escaped), so you don't have to worry about invalid URLs.

You can also initialize it with an object:

const params = new URLSearchParams({
  category: 'books',
  minPrice: '10',
  maxPrice: '50'
});

Key Takeaway: Use URLSearchParams to build clean, properly-encoded query strings for your GET requests—it handles the formatting and escaping automatically, preventing common URL construction errors.