{"id":15992,"library":"content-type","title":"HTTP Content-Type Header Utility","description":"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.","status":"active","version":"1.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/jshttp/content-type","tags":["javascript","content-type","http","req","res","rfc7231"],"install":[{"cmd":"npm install content-type","lang":"bash","label":"npm"},{"cmd":"yarn add content-type","lang":"bash","label":"yarn"},{"cmd":"pnpm add content-type","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"CommonJS is shown in documentation; for ESM, use `import * as` as it exports a module object with named functions.","wrong":"const contentType = require('content-type');","symbol":"contentType","correct":"import * as contentType from 'content-type';"},{"note":"While `contentType.parse` works with the `* as` import, named imports directly import the function. `content-type` does not export a default.","wrong":"import contentType from 'content-type'; // Then contentType.parse()","symbol":"parse","correct":"import { parse } from 'content-type';"},{"note":"Similar to `parse`, `format` is a named export. Direct named import is preferred for clarity and tree-shaking.","wrong":"import contentType from 'content-type'; // Then contentType.format()","symbol":"format","correct":"import { format } from 'content-type';"}],"quickstart":{"code":"import { parse, format } from 'content-type';\nimport http from 'http';\n\n// Example 1: Parsing a Content-Type string\ntry {\n  const headerString = 'text/html; charset=utf-8; boundary=xyz';\n  const parsed = parse(headerString);\n  console.log('Parsed string:', parsed); // { type: 'text/html', parameters: { charset: 'utf-8', boundary: 'xyz' } }\n} catch (error) {\n  console.error('Error parsing string:', error.message);\n}\n\n// Example 2: Formatting an object to a Content-Type string\ntry {\n  const objToFormat = {\n    type: 'application/json',\n    parameters: { charset: 'utf-8' }\n  };\n  const formatted = format(objToFormat);\n  console.log('Formatted object:', formatted); // 'application/json; charset=utf-8'\n} catch (error) {\n  console.error('Error formatting object:', error.message);\n}\n\n// Example 3: Parsing from an incoming HTTP request (simulated)\nconst server = http.createServer((req, res) => {\n  req.headers['content-type'] = 'application/x-www-form-urlencoded; encoding=UTF-8';\n\n  try {\n    const parsedReqHeader = parse(req);\n    console.log('Parsed from request:', parsedReqHeader);\n    res.writeHead(200, { 'Content-Type': format({\n      type: 'text/plain',\n      parameters: { charset: 'utf-8' }\n    }) });\n    res.end('Content-Type processed');\n  } catch (error) {\n    console.error('Error parsing request content-type:', error.message);\n    res.writeHead(400, { 'Content-Type': 'text/plain' });\n    res.end('Invalid Content-Type');\n  }\n});\n\nserver.listen(3000, () => {\n  console.log('Server listening on http://localhost:3000');\n  server.close(); // Close immediately for quickstart example\n});","lang":"javascript","description":"This quickstart demonstrates parsing Content-Type headers from strings and simulated HTTP requests, and formatting objects back into header strings."},"warnings":[{"fix":"```javascript\ntry {\n  const parsed = contentType.parse(headerValue);\n  // ... use parsed object\n} catch (error) {\n  if (error instanceof TypeError) {\n    console.error('Invalid Content-Type header:', error.message);\n    // Handle invalid header, e.g., return 400 Bad Request\n  } else {\n    throw error;\n  }\n}\n```","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"```javascript\nconst header = req.headers['content-type'];\nif (header) {\n  try {\n    const parsed = contentType.parse(header);\n    // ...\n  } catch (error) {\n    // Handle invalid format\n  }\n} else {\n  console.warn('Content-Type header is missing.');\n  // Handle missing header explicitly\n}\n```","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review existing usage of `media-typer` and ensure `content-type` provides equivalent functionality and handles error conditions identically. Specifically check how invalid input strings are handled, as `content-type` consistently throws `TypeError`.","message":"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.","severity":"breaking","affected_versions":"=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure 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.","cause":"The `parse` function was called without an argument or with `null`/`undefined`.","error":"TypeError: argument string is required"},{"fix":"Verify 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.","cause":"The string provided to `parse` does not conform to a valid HTTP Content-Type header format.","error":"TypeError: invalid media type"},{"fix":"Ensure the object passed to `contentType.format()` has a `type` property which is a valid media type string (e.g., `'application/json'`, `'text/plain'`).","cause":"When using `contentType.format(obj)`, the `obj.type` property is missing, `null`, `undefined`, or not a valid media type string.","error":"TypeError: invalid type"}],"ecosystem":"npm"}