HTTP Content-Type Header Utility
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
-
TypeError: argument string is required
cause The `parse` function was called without an argument or with `null`/`undefined`.fixEnsure that a non-empty string is always passed to `contentType.parse()`. If parsing from `req.headers['content-type']`, explicitly check if the header exists before calling parse. -
TypeError: invalid media type
cause The string provided to `parse` does not conform to a valid HTTP Content-Type header format.fixVerify the input string's syntax. It should follow the `type/subtype; parameter=value` structure. For example, `text/html`, `application/json; charset=utf-8` are valid, while `html` or `application/json;` (with trailing semicolon) might be invalid. -
TypeError: invalid type
cause When using `contentType.format(obj)`, the `obj.type` property is missing, `null`, `undefined`, or not a valid media type string.fixEnsure the object passed to `contentType.format()` has a `type` property which is a valid media type string (e.g., `'application/json'`, `'text/plain'`).
Warnings
- gotcha The `parse` function throws a `TypeError` if the input string is `null`, `undefined`, or an invalid Content-Type header format. Always wrap calls to `parse` in a `try...catch` block when dealing with potentially unreliable input, such as user-provided headers or network data.
- gotcha When parsing from `req` or `res` objects, `contentType.parse(req)` is a shortcut for `contentType.parse(req.headers['content-type'])`. If the `Content-Type` header is entirely missing from the `req.headers` object, this will result in a `TypeError` as `undefined` is passed to the underlying parsing logic. Ensure the header exists if you expect to parse it.
- breaking Version 1.0.0 was an initial implementation derived from `media-typer@0.3.0`. While intended to be a direct replacement for `media-typer`'s Content-Type specific features, users migrating from `media-typer` should verify their parsing and formatting logic, especially regarding error handling and edge cases, as the internal implementation changed.
Install
-
npm install content-type -
yarn add content-type -
pnpm add content-type
Imports
- contentType
const contentType = require('content-type');import * as contentType from 'content-type';
- parse
import contentType from 'content-type'; // Then contentType.parse()
import { parse } from 'content-type'; - format
import contentType from 'content-type'; // Then contentType.format()
import { format } from 'content-type';
Quickstart
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
});