Fast Content-Type Header Parser

3.0.0 · active · verified Tue Apr 21

fast-content-type-parse is a lightweight and performant utility designed to parse HTTP `Content-Type` headers in strict accordance with RFC 7231. Developed under the Fastify ecosystem, it aims for speed, outperforming Node.js's native `util#MIMEType` and other popular packages like `content-type`. The current stable version is `3.0.0`, with a release cadence that includes major updates for environmental compatibility and minor releases for maintenance. It provides both a strict parsing method that throws errors on invalid input and a 'safe' alternative that returns a default empty object for malformed headers. The package ships with TypeScript type definitions, ensuring robust development in TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both `parse` (strict, throws on error) and `safeParse` (returns empty object on error) methods for HTTP Content-Type headers.

import { parse, safeParse } from 'fast-content-type-parse';

// Example 1: Valid Content-Type header
try {
  const contentType = parse('application/json; charset=utf-8');
  console.log('Parsed (strict):', contentType); // { type: 'application/json', parameters: { charset: 'utf-8' } }
} catch (error) {
  console.error('Error parsing (strict):', error.message);
}

// Example 2: Invalid Content-Type header with strict parse (will throw)
try {
  const invalidContentType = parse('invalid-type;');
  console.log('Parsed (strict):', invalidContentType);
} catch (error) {
  console.error('Error parsing (strict):', error.message); // TypeError: Invalid Content-Type header string
}

// Example 3: Invalid Content-Type header with safeParse (will not throw)
const safeInvalidContentType = safeParse('invalid-type;');
console.log('Parsed (safe):', safeInvalidContentType); // { type: '', parameters: {} }

// Example 4: Another valid header with safeParse
const safeContentType = safeParse('text/html; boundary="foo"');
console.log('Parsed (safe):', safeContentType); // { type: 'text/html', parameters: { boundary: 'foo' } }

view raw JSON →