HTTP Content Negotiation

1.0.0 · active · verified Wed Apr 22

Negotiator is a lightweight, standalone utility for parsing and evaluating HTTP `Accept`, `Accept-Language`, `Accept-Encoding`, and `Accept-Charset` headers. It allows servers to determine the client's preferred content based on quality values (`q-factors`) specified in these headers. Primarily maintained by the `jshttp` organization, it serves as a core component for web frameworks like Express.js by abstracting complex RFC specifications for content negotiation. The current stable version is `1.0.0`. The package operates in a maintenance mode, with infrequent but significant major releases that often include breaking changes to align with evolving Node.js environments and best practices. It distinguishes itself by providing a robust and dependency-free solution for this specific HTTP concern.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing Negotiator with mock request headers and using its methods to determine preferred content types, languages, and encodings based on client preferences and available options.

import Negotiator from 'negotiator';

const mockRequest = {
  headers: {
    'accept': 'text/html, application/xhtml+xml, application/json;q=0.9, image/webp, */*;q=0.8',
    'accept-language': 'en-US,en;q=0.9,es;q=0.7',
    'accept-encoding': 'gzip, deflate, br;q=0.9, identity;q=0.5'
  }
};

const negotiator = new Negotiator(mockRequest);

console.log('Preferred Media Types (all):', negotiator.mediaTypes());
console.log('Preferred Media Type (available):', negotiator.mediaType(['application/json', 'text/plain']));

console.log('Preferred Languages (all):', negotiator.languages());
console.log('Preferred Language (available):', negotiator.language(['es', 'fr']));

console.log('Preferred Encodings (all):', negotiator.encodings());
console.log('Preferred Encoding (available):', negotiator.encoding(['gzip', 'br', 'identity']));

/* Example Output:
Preferred Media Types (all): [ 'text/html', 'application/xhtml+xml', 'application/json', 'image/webp', '*/*' ]
Preferred Media Type (available): application/json
Preferred Languages (all): [ 'en-US', 'en', 'es' ]
Preferred Language (available): es
Preferred Encodings (all): [ 'gzip', 'br', 'identity', 'deflate' ]
Preferred Encoding (available): gzip
*/

view raw JSON →