Query Params & Headers
URLSearchParams, custom request headers, and reading response headers
Skills taught: api.urlsearchparams, api.request-headers, api.response-headers, api.accept-header
Query parameters and request headers
// ── URLSearchParams — safe query string building ──
const params = new URLSearchParams({
category: 'electronics',
sort: 'price_asc',
page: '2',
q: 'USB-C hub', // spaces + special chars → encoded automatically
});
console.log(params.toString());
// → category=electronics&sort=price_asc&page=2&q=USB-C+hub
const url = `https://api.example.com/products?${params}`;
// ── URL class for full URLs ──
const u = new URL('https://api.github.com/search/repositories');
u.searchParams.set('q', 'react language:typescript');
u.searchParams.set('sort', 'stars');
u.searchParams.set('per_page', '10');
console.log(u.toString());
// → https://api.github.com/search/repositories?q=react+language%3Atypescript&sort=stars&per_page=10
// ── Request headers ──
const res = await fetch(url, {
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer my-token',
'X-Client-Version': '1.0.0',
// 'Content-Type' — only needed for POST/PUT/PATCH with a body
},
});
// ── Reading response headers ──
console.log('Content-Type:', res.headers.get('content-type'));
console.log('Rate Limit:', res.headers.get('x-ratelimit-limit'));
console.log('Remaining:', res.headers.get('x-ratelimit-remaining'));
console.log('Reset Time:', res.headers.get('x-ratelimit-reset'));
console.log('Request ID:', res.headers.get('x-request-id')); // for support tickets
// ── Pagination via Link header (GitHub style) ──
const link = res.headers.get('link');
// → '<https://api.example.com/users?page=3>; rel="next", <...>; rel="last"'
if (link) {
const nextMatch = link.match(/<([^>]+)>; rel="next"/);
const nextUrl = nextMatch?.[1];
console.log('Next page:', nextUrl);
}
Tip: Never put secrets (API keys, tokens) in query parameters — they appear in browser history, server logs, and Referer headers. Always put them in the Authorization header: `'Authorization': 'Bearer your-token'`.
Frequently Asked Questions
How do I read all response headers?
Use `response.headers.forEach((value, name) => console.log(name, value))`. Or iterate with `for (const [name, value] of response.headers.entries())`. Note: for security reasons, JavaScript can only read 'simple' response headers plus headers the server explicitly exposes via `Access-Control-Expose-Headers`. Custom headers like `X-RateLimit-Remaining` must be listed in that header to be readable from cross-origin requests.