response-is
v0.0.0-rc
Published
🍬 Understand what type the response is by content type string
Downloads
2
Maintainers
Readme
response-is
The Content-Type
header can sometimes be unclear. This library aims to help you determine the type of content you're dealing with.
Disclaimers
- This module is exclusively an ESM module.
- This module is intended for server side use. It will not work in the browser: The browser "fetch" does not have access to the response headers.
Example
import { responseIs } from "response-is";
const response = await fetch("https://omrilotan.com");
const is = responseIs(response);
if (is.html) {
// do something
} else if (is.json) {
// do something else
} else {
// do something else
}
Functionality
Available getters
html
, xhtml
, form
, json
, xml
, text
, stylesheet
, javascript
, font
, image
, icon
, video
, audio
, stream
, binary
, bmp
, css
, gif
, ico
, jpeg
, jpg
, js
, mjs
, mid
, midi
, mp3
, mp4
, mpeg
, ogg
, otf
, png
, svg
, svgz
, ttf
, webm
, webp
, woff
, woff2
Getter truthfulness is not nessecarily mutually exclusive. For example, the Content-Type "application/xhtml+xml" will return true
for both is.html
and is.xhtml
, while the Content-Type "text/html" will return true
for is.html
but not for is.text
.
The Content-Type "text/javascript" will return true
for is.javascript
, is.js
and is.text
, so make sure you prioritize your checks. For example is.javascript
should be checked before is.text
.
Additional functions
toJSON
- returns a JSON representation of the content typetoString
- returns the value of the content type header
const is = responseIs(
new Response(null, headers: new Headers({
"content-type": "text/html"
}))
);
is.toJSON(); // { mediaType: "text", subType: "html" }
toString
- returns the value of the content type header
const is = responseIs({
headers: {
"content-type": "text/html; charset=utf-8",
},
});
is.toString(); // text/html
Use Case
This example use case detects "Cache Deception" attack where users create a URL with the suffix ".js" while the route returns actual data.
import { responseIs } from "response-is";
const CACHABLE_EXTENSIONS = ["js", "css", "mjs"]; // See default cache behaviour: https://developers.cloudflare.com/cache/concepts/default-cache-behavior/
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const response = await fetch(request);
const url = new URL(request.url);
const extension = url.pathname.split(".").pop();
if (!CACHABLE_EXTENSIONS.includes(extension)) {
const is = responseIs(response);
if (!is[extension] === false) {
// clear from cache
const cache = caches.default;
ctx.waitUntil(cache.delete(request.url));
response.headers.set("Cf-Cache-Status", "BYPASS");
}
}
return response;
},
};