@kikobeats/set-content-type
v1.0.1
Published
Set the response content-type based on the payload bytes
Maintainers
Readme
@kikobeats/set-content-type
Set the response
content-typebased on the payload bytes.
Some upstreams (e.g. S3/CloudFront origins) stream a response without a content-type header. When you proxy those bytes, the browser can't tell it's an image and renders it as raw text — worse if you send x-content-type-options: nosniff.
This module fixes that: pipe the payload through it and, only when the response doesn't already have a content-type, it detects the type from the first bytes (via file-type) and sets it on the response before anything is written.
Install
$ npm install @kikobeats/set-content-type --saveUsage
Insert it between your upstream and the response:
const setContentType = require('@kikobeats/set-content-type')
server.on('request', (req, res) => {
upstream.pipe(setContentType(res))
})The returned stream is already wired to res, so you only pipe once. If the
upstream already provided a content-type, it is left untouched.
API
setContentType(res)
res
Required
Type: http.ServerResponse
The outgoing response whose content-type should be set when missing.
It returns a Transform
stream already piped to res — pipe your upstream into it and you are done.
The first chunk is inspected to detect the type — file-type works on partial
data, so the whole payload is never buffered. The chunk is held until detection
resolves, guaranteeing the header is set before the first write to res.
The header is not set when:
resalready has acontent-typeheader.- the response has already been sent (
res.headersSent). - the payload type can not be recognized.
License
@kikobeats/set-content-type © Kiko Beats, released under the MIT License. Authored and maintained by Kiko Beats with help from contributors.
kikobeats.com · GitHub Kiko Beats · Twitter @kikobeats
