Skip to content

Instantly share code, notes, and snippets.

@aabccd021
Created October 30, 2024 01:26
Show Gist options
  • Save aabccd021/1ab1f7862cdf0db7691fba749d884f2a to your computer and use it in GitHub Desktop.
Save aabccd021/1ab1f7862cdf0db7691fba749d884f2a to your computer and use it in GitHub Desktop.
Bun mime middleware
import mimes from "mime";
type RequestHandler = (req: Request) => Promise<Response>;
export function middleware(fetch: RequestHandler): RequestHandler {
return async (req) => {
if (req.method !== "GET") {
return fetch(req);
}
const response = await fetch(req);
if (response.status !== 200) {
return response;
}
const contentTypeAlereadySet =
response.headers.get("Content-Type") !== null;
if (contentTypeAlereadySet) {
return response;
}
const path = new URL(req.url).pathname;
const extension = path.split(".").at(-1);
if (extension === undefined) {
return response;
}
const mimeType = mimes.getType(extension);
if (mimeType === null) {
return response;
}
response.headers.set("Content-Type", mimeType);
return response;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment