@prexjs/content-type
v1.0.0
Published
Create and parse HTTP Content-Type headers and media types according to RFC 9110.
Readme
@prexjs/content-type
Create and parse HTTP Content-Type headers and media types according to RFC 9110.
@prexjs/content-type is a high-performance utility for parsing and formatting HTTP Content-Type headers and MIME types according to RFC 9110 standards.
Features
- Parse
Content-Typeheader strings into type and parameter objects. - Format structured objects into valid
Content-Typeheader strings with proper quote escaping. - Validate media types and token characters per RFC 9110.
- Fast ASCII character bitmask lookup for high throughput.
- Zero runtime dependencies.
- Dual ES Module (
.mjs) and CommonJS (.cjs) support with TypeScript definitions.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/content-type
# pnpm
pnpm add @prexjs/content-type
# Yarn
yarn add @prexjs/content-type
# Bun
bun add @prexjs/content-typeQuick start
import contentType from '@prexjs/content-type';
// Parse a Content-Type header
const parsed = contentType.parse('text/html; charset=utf-8');
console.log(parsed.type); // 'text/html'
console.log(parsed.parameters); // { charset: 'utf-8' }
// Format an object to a header string
const header = contentType.format({
type: 'application/json',
parameters: { charset: 'utf-8' },
});
console.log(header); // 'application/json; charset=utf-8'Both default and named exports are supported:
import contentType, {
parse,
format,
isTypeValid,
isTokenValid,
type ContentType,
type ParsedContentType,
type Parameters,
type ParseOptions,
} from '@prexjs/content-type';Examples
Parsing headers with parameters
import { parse } from '@prexjs/content-type';
const obj = parse('multipart/form-data; boundary="something_special"');
console.log(obj.type); // 'multipart/form-data'
console.log(obj.parameters.boundary); // 'something_special'Formatting headers
import { format } from '@prexjs/content-type';
const header = format({
type: 'image/svg+xml',
parameters: {
charset: 'utf-8',
},
});
// 'image/svg+xml; charset=utf-8'Type and token validation
import { isTypeValid, isTokenValid } from '@prexjs/content-type';
console.log(isTypeValid('application/json')); // true
console.log(isTypeValid('invalid type')); // false
console.log(isTokenValid('charset')); // true
console.log(isTokenValid('token with spaces')); // falseCompatibility
@prexjs/content-type is designed for JavaScript and TypeScript projects. It is distributed with ES Modules (.mjs), CommonJS (.cjs), and TypeScript declarations. It runs in any modern JavaScript runtime (Node.js, Deno, Bun, browser) without external dependencies.
License
This project is licensed under the MIT License. See LICENSE for the full license text.
Related projects
- prex.js — prex.js monorepo and ecosystem.
