bun-remix icon indicating copy to clipboard operation
bun-remix copied to clipboard

Add cache control header for static resources

Open znycheporuk opened this issue 1 year ago • 0 comments

Actually I wanted to make PR, but repo is readonly, so just will drop code right here. I added Cache-Control headers to the example, same as in remix's express template

Just replace current server.js with a following code:

import * as Bun from "bun";
import * as fs from "node:fs";

import {
  broadcastDevReady,
  createRequestHandler,
} from "@remix-run/server-runtime";

const BUILD_PATH = "./build/index.js";
const STATIC_PATH = "./public";

const HOUR_IN_SECONDS = 60 * 60;
const YEAR_IN_SECONDS = 365 * 24 * HOUR_IN_SECONDS;

let build = await import(BUILD_PATH);
if (build.dev) {
  broadcastDevReady(build);
}

export default {
  async fetch(request) {
    const url = new URL(request.url);

    try {
      const filePath = STATIC_PATH + url.pathname;
      if (fs.statSync(filePath).isFile()) {
        const file = Bun.file(filePath);
        
        let cacheControl;
        if (url.pathname.startsWith("/build/")) {
          cacheControl = `immutable, max-age=${ YEAR_IN_SECONDS }`;
        } else {
          cacheControl = `max-age=${ HOUR_IN_SECONDS }`;
        }
        return new Response(file, { headers: { "Cache-Control": cacheControl }});      
      }
    } catch {}

    build = await import(BUILD_PATH);
    const handler = createRequestHandler(build, process.env.NODE_ENV);

    const loadContext = {};

    return handler(request, loadContext);
  },
  error() {
    return new Response(null, { status: 404 });
  },
};

znycheporuk avatar Jun 30 '23 01:06 znycheporuk