A light-weight module that brings Fetch API to Node.js
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
HTTP header manipulation with case-insensitive operations and Web Standards compatibility. The Headers class provides a comprehensive interface for managing HTTP headers in both requests and responses.
Manages HTTP headers with case-insensitive operations and various initialization options.
/**
* HTTP Headers class for manipulating request and response headers
*/
class Headers {
constructor(init?: HeadersInit);
// Core methods
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
// Iteration methods
forEach(callback: (value: string, key: string, headers: Headers) => void, thisArg?: any): void;
entries(): IterableIterator<[string, string]>;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
// Node.js extension
raw(): Record<string, string[]>;
}
type HeadersInit = Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>;Usage Examples:
import { Headers } from 'node-fetch';
// Create empty headers
const headers = new Headers();
// Create from object
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
});
// Create from array of pairs
const headers = new Headers([
['Content-Type', 'application/json'],
['X-Custom-Header', 'value']
]);
// Create from existing Headers instance
const existingHeaders = new Headers({ 'Accept': 'application/json' });
const newHeaders = new Headers(existingHeaders);Methods for adding, modifying, and removing HTTP headers.
interface HeaderManipulation {
/**
* Adds a value to an existing header or creates a new header
* @param name - Header name (case-insensitive)
* @param value - Header value to append
*/
append(name: string, value: string): void;
/**
* Removes a header entirely
* @param name - Header name to remove (case-insensitive)
*/
delete(name: string): void;
/**
* Gets the value of a header
* @param name - Header name (case-insensitive)
* @returns Header value or null if not found
*/
get(name: string): string | null;
/**
* Checks if a header exists
* @param name - Header name (case-insensitive)
* @returns True if header exists
*/
has(name: string): boolean;
/**
* Sets a header value, replacing any existing value
* @param name - Header name (case-insensitive)
* @param value - Header value to set
*/
set(name: string, value: string): void;
}Usage Examples:
const headers = new Headers();
// Set headers
headers.set('Content-Type', 'application/json');
headers.set('Authorization', 'Bearer token123');
// Append to existing header (creates comma-separated values)
headers.append('Accept', 'application/json');
headers.append('Accept', 'application/xml');
console.log(headers.get('Accept')); // 'application/json, application/xml'
// Check if header exists
if (headers.has('Authorization')) {
console.log('Authorization header is present');
}
// Get header value
const contentType = headers.get('Content-Type');
console.log(contentType); // 'application/json'
// Delete header
headers.delete('Authorization');
console.log(headers.has('Authorization')); // false
// Case-insensitive operations
headers.set('content-type', 'text/plain');
console.log(headers.get('Content-Type')); // 'text/plain'Methods for iterating over headers with support for modern JavaScript iteration patterns.
interface HeaderIteration {
/**
* Executes a callback for each header
* @param callback - Function to execute for each header
* @param thisArg - Value to use as 'this' when executing callback
*/
forEach(callback: (value: string, key: string, headers: Headers) => void, thisArg?: any): void;
/**
* Returns an iterator for [name, value] pairs
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns an iterator for header names
*/
keys(): IterableIterator<string>;
/**
* Returns an iterator for header values
*/
values(): IterableIterator<string>;
/**
* Default iterator (same as entries())
*/
[Symbol.iterator](): IterableIterator<[string, string]>;
}Usage Examples:
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'X-Custom-Header': 'custom-value'
});
// Use forEach
headers.forEach((value, name) => {
console.log(`${name}: ${value}`);
});
// Use for...of with entries
for (const [name, value] of headers.entries()) {
console.log(`${name}: ${value}`);
}
// Use for...of with default iterator
for (const [name, value] of headers) {
console.log(`${name}: ${value}`);
}
// Iterate over keys
for (const name of headers.keys()) {
console.log(`Header name: ${name}`);
}
// Iterate over values
for (const value of headers.values()) {
console.log(`Header value: ${value}`);
}
// Convert to array
const headerArray = [...headers.entries()];
const headerNames = [...headers.keys()];
const headerValues = [...headers.values()];Node.js specific extension for accessing raw header values as arrays.
interface RawHeaders {
/**
* Returns raw headers as an object with arrays of values
* @returns Object mapping header names to arrays of values
*/
raw(): Record<string, string[]>;
}Usage Examples:
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Accept', 'application/xml');
headers.append('Set-Cookie', 'session=abc123');
headers.append('Set-Cookie', 'theme=dark');
// Get raw headers (useful for Set-Cookie and similar headers)
const rawHeaders = headers.raw();
console.log(rawHeaders);
// {
// 'accept': ['application/json', 'application/xml'],
// 'set-cookie': ['session=abc123', 'theme=dark']
// }
// Access individual cookie values
const cookies = headers.raw()['set-cookie'];
cookies.forEach(cookie => {
console.log('Cookie:', cookie);
});Examples of working with common HTTP headers in typical scenarios.
// Common content types
type ContentType =
| 'application/json'
| 'application/x-www-form-urlencoded'
| 'multipart/form-data'
| 'text/plain'
| 'text/html'
| 'application/octet-stream';
// Common authentication patterns
type AuthHeader =
| `Bearer ${string}`
| `Basic ${string}`
| `Digest ${string}`;Usage Examples:
// JSON API headers
const jsonHeaders = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...'
});
// Form submission headers
const formHeaders = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
// File upload headers (multipart is set automatically by FormData)
const uploadHeaders = new Headers({
'Authorization': 'Bearer token123'
// Content-Type will be set automatically when using FormData
});
// Basic authentication
const credentials = btoa('username:password');
const authHeaders = new Headers({
'Authorization': `Basic ${credentials}`
});
// Custom headers for API versioning
const apiHeaders = new Headers({
'Accept': 'application/vnd.api+json',
'X-API-Version': '2.1',
'X-Client-ID': 'myapp-v1.0'
});
// Cache control headers
const cacheHeaders = new Headers({
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});How headers work with Request and Response objects.
interface RequestWithHeaders {
readonly headers: Headers;
}
interface ResponseWithHeaders {
readonly headers: Headers;
}Usage Examples:
import fetch, { Request, Response, Headers } from 'node-fetch';
// Using headers with Request
const requestHeaders = new Headers({
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
});
const request = new Request('https://api.example.com/data', {
method: 'GET',
headers: requestHeaders
});
// Access request headers
console.log(request.headers.get('User-Agent')); // 'MyApp/1.0'
// Using headers with fetch
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token123',
'Accept': 'application/json'
}
});
// Access response headers
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Server'));
console.log(response.headers.get('Date'));
// Get all Set-Cookie headers (common pattern)
const setCookieHeaders = response.headers.raw()['set-cookie'] || [];
setCookieHeaders.forEach(cookie => {
console.log('Set-Cookie:', cookie);
});Headers class automatically validates header names and values according to HTTP specifications.
interface HeaderValidation {
// Throws TypeError for invalid header names or values
validateHeaderName(name: string): void;
validateHeaderValue(name: string, value: string): void;
}Usage Examples:
const headers = new Headers();
try {
// Valid headers
headers.set('Content-Type', 'application/json');
headers.set('X-Custom-Header', 'valid-value');
// Invalid header name (will throw TypeError)
headers.set('Invalid Header Name', 'value'); // Spaces not allowed
} catch (error) {
console.error('Invalid header:', error.message);
// Error: Header name must be a valid HTTP token [Invalid Header Name]
}
try {
// Invalid header value (will throw TypeError)
headers.set('Custom-Header', 'value\nwith\nnewlines'); // Control characters not allowed
} catch (error) {
console.error('Invalid header value:', error.message);
// Error: Invalid character in header content ["Custom-Header"]
}