HTTP Content-Type Header Utility

1.0.5 · active · verified Tue Apr 21

The `content-type` package provides a robust utility for creating and parsing HTTP Content-Type headers in Node.js applications, adhering strictly to RFC 7231. It is currently at version 1.0.5, indicating a mature and stable library. The release cadence is infrequent, primarily focusing on performance improvements and minor fixes, suggesting a low-churn, well-maintained codebase. Its core functionality involves parsing a Content-Type string (or directly from `req`/`res` objects) into an object with `type` and `parameters`, and conversely, formatting such an object back into a valid header string. This library is a foundational component for many HTTP servers and clients that need reliable content negotiation, differentiating itself through its minimalist API and strict RFC compliance without unnecessary abstractions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing Content-Type headers from strings and simulated HTTP requests, and formatting objects back into header strings.

import { parse, format } from 'content-type';
import http from 'http';

// Example 1: Parsing a Content-Type string
try {
  const headerString = 'text/html; charset=utf-8; boundary=xyz';
  const parsed = parse(headerString);
  console.log('Parsed string:', parsed); // { type: 'text/html', parameters: { charset: 'utf-8', boundary: 'xyz' } }
} catch (error) {
  console.error('Error parsing string:', error.message);
}

// Example 2: Formatting an object to a Content-Type string
try {
  const objToFormat = {
    type: 'application/json',
    parameters: { charset: 'utf-8' }
  };
  const formatted = format(objToFormat);
  console.log('Formatted object:', formatted); // 'application/json; charset=utf-8'
} catch (error) {
  console.error('Error formatting object:', error.message);
}

// Example 3: Parsing from an incoming HTTP request (simulated)
const server = http.createServer((req, res) => {
  req.headers['content-type'] = 'application/x-www-form-urlencoded; encoding=UTF-8';

  try {
    const parsedReqHeader = parse(req);
    console.log('Parsed from request:', parsedReqHeader);
    res.writeHead(200, { 'Content-Type': format({
      type: 'text/plain',
      parameters: { charset: 'utf-8' }
    }) });
    res.end('Content-Type processed');
  } catch (error) {
    console.error('Error parsing request content-type:', error.message);
    res.writeHead(400, { 'Content-Type': 'text/plain' });
    res.end('Invalid Content-Type');
  }
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
  server.close(); // Close immediately for quickstart example
});

view raw JSON →