or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cancellation.mddata-transformation.mderror-handling.mdheaders.mdhttp-client.mdindex.mdinstance-management.mdinterceptors.md
tile.json

headers.mddocs/

Headers Management

Advanced header manipulation with type-safe operations, automatic content-type handling, and specialized methods for common HTTP headers.

Capabilities

AxiosHeaders Class

Powerful header management class with advanced manipulation methods and type safety.

/**
 * Advanced headers management class
 */
class AxiosHeaders {
  constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
  
  /** Allow bracket notation access */
  [key: string]: any;
  
  /** Set header value with optional rewrite control */
  set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
  
  /** Get header value with optional parsing */
  get(headerName: string, parser: RegExp): RegExpExecArray | null;
  get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
  
  /** Check if header exists */
  has(header: string, matcher?: AxiosHeaderMatcher): boolean;
  
  /** Delete header(s) */
  delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
  
  /** Clear headers matching criteria */
  clear(matcher?: AxiosHeaderMatcher): boolean;
  
  /** Normalize header names */
  normalize(format: boolean): AxiosHeaders;
  
  /** Concatenate with other headers */
  concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
  
  /** Convert to plain object */
  toJSON(asStrings?: boolean): RawAxiosHeaders;
}

type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;

Usage Examples:

import { AxiosHeaders } from "axios";

// Create headers from object
const headers = new AxiosHeaders({
  "Content-Type": "application/json",
  "Authorization": "Bearer token123"
});

// Set individual headers
headers.set("X-Custom-Header", "custom-value");
headers.set("Accept", "application/json");

// Set multiple headers at once
headers.set({
  "User-Agent": "MyApp/1.0",
  "X-API-Version": "v2"
});

// Get header values
const contentType = headers.get("Content-Type");
const auth = headers.get("authorization"); // Case-insensitive

// Check if header exists
if (headers.has("Authorization")) {
  console.log("Auth header is present");
}

// Delete headers
headers.delete("X-Temporary-Header");

// Convert to plain object
const plainHeaders = headers.toJSON();
console.log(plainHeaders);

Static Methods

Factory and utility methods for header creation and manipulation.

/**
 * Create AxiosHeaders from various sources
 * @param thing - Source to create headers from
 * @returns New AxiosHeaders instance
 */
static AxiosHeaders.from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;

/**
 * Create header accessor for specific header
 * @param header - Header name or names
 * @returns AxiosHeaders with accessor methods
 */
static AxiosHeaders.accessor(header: string | string[]): AxiosHeaders;

/**
 * Concatenate multiple header sources
 * @param targets - Header sources to concatenate
 * @returns New AxiosHeaders with combined headers
 */
static AxiosHeaders.concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;

Usage Examples:

// Create from different sources
const fromObject = AxiosHeaders.from({
  "Content-Type": "application/json"
});

const fromString = AxiosHeaders.from("Content-Type: application/json\r\nAuthorization: Bearer token");

const fromExisting = AxiosHeaders.from(existingHeaders);

// Create accessor
const contentTypeAccessor = AxiosHeaders.accessor("Content-Type");

// Concatenate headers
const combined = AxiosHeaders.concat(
  { "Accept": "application/json" },
  new AxiosHeaders({ "Authorization": "Bearer token" }),
  "X-Custom: value"
);

Specialized Header Methods

Type-safe methods for common HTTP headers with automatic parsing and validation.

// Content-Type management
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentType(parser?: RegExp): RegExpExecArray | null;
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentType(matcher?: AxiosHeaderMatcher): boolean;

// Content-Length management
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentLength(parser?: RegExp): RegExpExecArray | null;
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;

// Accept header management
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAccept(parser?: RegExp): RegExpExecArray | null;
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAccept(matcher?: AxiosHeaderMatcher): boolean;

// User-Agent management
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getUserAgent(parser?: RegExp): RegExpExecArray | null;
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;

// Content-Encoding management
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;

// Authorization management
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAuthorization(parser?: RegExp): RegExpExecArray | null;
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;

// Set-Cookie handling
getSetCookie(): string[];

type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' 
  | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';

Usage Examples:

const headers = new AxiosHeaders();

// Content-Type management
headers.setContentType("application/json");
headers.setContentType("multipart/form-data", true); // Force rewrite

const contentType = headers.getContentType();
console.log(contentType); // "multipart/form-data"

if (headers.hasContentType(/^application\//)) {
  console.log("Application content type");
}

// Authorization management
headers.setAuthorization("Bearer eyJhbGciOiJIUzI1NiIs...");
const authToken = headers.getAuthorization(/Bearer (.+)/);
console.log(authToken); // ["Bearer eyJhbGc...", "eyJhbGc..."]

// Accept header
headers.setAccept("application/json, text/plain, */*");

// User-Agent
headers.setUserAgent("MyApp/1.0 (Platform/Version)");

// Content-Length (usually set automatically)
headers.setContentLength(1024);

// Set-Cookie handling (typically in responses)
const cookies = headers.getSetCookie(); // Returns array of cookie strings

Header Iteration

Iterate over headers using standard iteration methods.

/**
 * Iterator for header name-value pairs
 */
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;

Usage Examples:

const headers = new AxiosHeaders({
  "Content-Type": "application/json",
  "Authorization": "Bearer token",
  "Accept": "application/json"
});

// Iterate over all headers
for (const [name, value] of headers) {
  console.log(`${name}: ${value}`);
}

// Convert to array
const headerEntries = Array.from(headers);

// Use with destructuring
const headerMap = new Map(headers);

Request and Response Header Types

Type definitions for request and response headers.

// Request headers
interface RawAxiosRequestHeaders extends Partial<RawAxiosHeaders & {
  'Accept': AxiosHeaderValue;
  'Content-Length': AxiosHeaderValue;
  'User-Agent': AxiosHeaderValue;
  'Content-Encoding': AxiosHeaderValue;
  'Authorization': AxiosHeaderValue;
  'Content-Type': ContentType;
}> {}

type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;

// Response headers
interface RawAxiosResponseHeaders extends Partial<RawAxiosHeaders & {
  'Server': AxiosHeaderValue;
  'Content-Type': AxiosHeaderValue;
  'Content-Length': AxiosHeaderValue;
  'Cache-Control': AxiosHeaderValue;
  'Content-Encoding': AxiosHeaderValue;
  'set-cookie': string[];
}> {}

type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;

// Method-specific headers
type MethodsHeaders = Partial<{
  [Key in Method as Lowercase<Key>]: AxiosHeaders;
} & {common: AxiosHeaders}>;

Default Headers Configuration

Configure default headers for different HTTP methods.

interface HeadersDefaults {
  common: RawAxiosRequestHeaders;
  delete: RawAxiosRequestHeaders;
  get: RawAxiosRequestHeaders;
  head: RawAxiosRequestHeaders;
  post: RawAxiosRequestHeaders;
  put: RawAxiosRequestHeaders;
  patch: RawAxiosRequestHeaders;
  options?: RawAxiosRequestHeaders;
  purge?: RawAxiosRequestHeaders;
  link?: RawAxiosRequestHeaders;
  unlink?: RawAxiosRequestHeaders;
}

Usage Examples:

import axios from "axios";

// Set common headers for all requests
axios.defaults.headers.common["Authorization"] = "Bearer token123";
axios.defaults.headers.common["X-API-Version"] = "v2";

// Set method-specific headers
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.get["Accept"] = "application/json";

// Instance-specific headers
const apiClient = axios.create();
apiClient.defaults.headers.common["User-Agent"] = "MyApp/1.0";
apiClient.defaults.headers.post["Content-Type"] = "application/json";

// Headers in request config
const response = await axios.get("/api/users", {
  headers: {
    "Accept": "application/json",
    "X-Request-ID": generateRequestId()
  }
});

// Using AxiosHeaders in config
const customHeaders = new AxiosHeaders()
  .setAuthorization("Bearer token")
  .setContentType("application/json")
  .set("X-Custom", "value");

const postResponse = await axios.post("/api/data", payload, {
  headers: customHeaders
});

Header Matching and Filtering

Advanced header matching with custom matchers.

Usage Examples:

const headers = new AxiosHeaders({
  "Content-Type": "application/json",
  "X-Custom-Header": "custom-value",
  "Authorization": "Bearer token123",
  "Accept": "application/json, text/plain"
});

// String matcher (case-insensitive)
const hasAuth = headers.has("authorization");

// RegExp matcher
const hasJsonContent = headers.has("Content-Type", /application\/json/);

// Function matcher
const hasCustomHeaders = headers.has("", (value, name) => {
  return name.toLowerCase().startsWith("x-");
});

// Delete headers matching pattern
headers.delete("", /^x-/i); // Delete all X- headers

// Clear headers with custom matcher
headers.clear((value, name) => {
  return name.toLowerCase().includes("temp");
});

// Conditional header setting
const rewriteIfEmpty = (value, name) => !value || value.length === 0;
headers.set("Accept", "application/json", rewriteIfEmpty);

Advanced Header Patterns

Complex header management patterns for real-world applications.

Usage Examples:

// Header builder pattern
class HeaderBuilder {
  constructor() {
    this.headers = new AxiosHeaders();
  }
  
  auth(token) {
    this.headers.setAuthorization(`Bearer ${token}`);
    return this;
  }
  
  json() {
    this.headers.setContentType("application/json");
    this.headers.setAccept("application/json");
    return this;
  }
  
  userAgent(ua) {
    this.headers.setUserAgent(ua);
    return this;
  }
  
  custom(name, value) {
    this.headers.set(name, value);
    return this;
  }
  
  build() {
    return this.headers;
  }
}

// Usage
const headers = new HeaderBuilder()
  .auth("token123")
  .json()
  .userAgent("MyApp/1.0")
  .custom("X-Request-ID", generateId())
  .build();

// Conditional headers
function buildHeaders(options = {}) {
  const headers = new AxiosHeaders();
  
  if (options.auth) {
    headers.setAuthorization(`Bearer ${options.auth}`);
  }
  
  if (options.contentType) {
    headers.setContentType(options.contentType);
  } else {
    headers.setContentType("application/json");
  }
  
  if (options.accept) {
    headers.setAccept(options.accept);
  }
  
  if (options.custom) {
    Object.entries(options.custom).forEach(([name, value]) => {
      headers.set(name, value);
    });
  }
  
  return headers;
}

// Header merging strategy
function mergeHeaders(base, override) {
  const result = AxiosHeaders.from(base);
  
  if (override) {
    return result.concat(override);
  }
  
  return result;
}

// Dynamic headers based on environment
function getEnvironmentHeaders() {
  const headers = new AxiosHeaders();
  
  if (process.env.NODE_ENV === "development") {
    headers.set("X-Debug", "true");
  }
  
  if (process.env.API_VERSION) {
    headers.set("X-API-Version", process.env.API_VERSION);
  }
  
  return headers;
}