Negotiate.js

raw JSON →
1.0.1 verified Sat Apr 25 auth: no javascript maintenance

JavaScript implementation of the HTTP preemptive content negotiation algorithm as defined in the original HTTP 1.1 draft spec. Stable version 1.0.1, no longer actively developed. Differentiators: implements the original draft negotiation algorithm (not the final RFC), handles media type, language, charset, and encoding negotiation. Suitable for Node.js HTTP servers needing automatic variant selection. Alternative to content-negotiation libraries that follow the final RFC.

error Negotiate is not defined
cause Using the library without importing it first.
fix
Add const Negotiate = require('negotiate'); or import Negotiate from 'negotiate'; at the top of your file.
error Cannot find module 'negotiate'
cause Package not installed or missing from node_modules.
fix
Run npm install negotiate --save to install the package.
error TypeError: variants is not iterable
cause Passing a single object instead of an array of variants.
fix
Wrap your variant in an array: Negotiate.choose([variant], request);
gotcha The algorithm implements the original HTTP 1.1 draft spec, not the final RFC 7231. Results may differ from other content negotiation libraries.
fix Ensure your expected negotiation behavior matches the draft algorithm; test with various Accept headers.
gotcha The package has not been updated since 2015 and depends on older Node.js patterns. No security patches have been applied.
fix Consider using an actively maintained alternative like 'content-negotiator' or implement RFC 7231 negotiation yourself.
gotcha Variant quality factor defaults to 1.0 if not specified, which may cause unexpected selections if you omit quality values.
fix Always explicitly set the quality property on each variant to control priority.
npm install negotiate
yarn add negotiate
pnpm add negotiate

Shows how to define variants and select the best representation for an HTTP request using negotiate.choose().

import Negotiate from 'negotiate';

const variants = [
  {
    method: 'GET',
    type: 'text/html',
    language: 'en-ca',
    charset: 'iso-8859-1',
    encoding: null,
    quality: 1.0,
    length: 36741,
    filename: 'blog.html'
  },
  {
    method: 'GET',
    type: 'application/atom+xml',
    language: 'en',
    charset: 'utf-8',
    encoding: 'gzip',
    quality: 0.8,
    length: 12987,
    filename: 'blog.atom.gzip'
  }
];

const request = {
  url: '/blog',
  method: 'GET',
  headers: {
    'accept': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
    'accept-language': 'en-US,en;q=0.8',
    'accept-encoding': 'gzip,deflate,sdch',
    'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
  }
};

const responses = Negotiate.choose(variants, request);
console.log(responses[0]);