middleware-serve-static-assets.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /// <reference path="middleware-serve-static-assets.d.ts"/>
  2. import {
  3. getAssetFromKV,
  4. NotFoundError,
  5. MethodNotAllowedError,
  6. serveSinglePageApp,
  7. } from "@cloudflare/kv-asset-handler";
  8. import type { Options } from "@cloudflare/kv-asset-handler";
  9. import { spaMode, cacheControl } from "config:middleware/serve-static-assets";
  10. import type * as kvAssetHandler from "@cloudflare/kv-asset-handler";
  11. import manifest from "__STATIC_CONTENT_MANIFEST";
  12. const ASSET_MANIFEST = JSON.parse(manifest);
  13. import type { Middleware } from "./common";
  14. const staticAssets: Middleware = async (request, env, _ctx, middlewareCtx) => {
  15. let options: Partial<Options> = {
  16. ASSET_MANIFEST,
  17. ASSET_NAMESPACE: env.__STATIC_CONTENT,
  18. cacheControl: cacheControl,
  19. mapRequestToAsset: spaMode ? serveSinglePageApp : undefined,
  20. };
  21. try {
  22. const page = await (getAssetFromKV as typeof kvAssetHandler.getAssetFromKV)(
  23. {
  24. request,
  25. waitUntil(promise) {
  26. return _ctx.waitUntil(promise);
  27. },
  28. },
  29. options
  30. );
  31. // allow headers to be altered
  32. const response = new Response(page.body, page);
  33. response.headers.set("X-XSS-Protection", "1; mode=block");
  34. response.headers.set("X-Content-Type-Options", "nosniff");
  35. response.headers.set("X-Frame-Options", "DENY");
  36. response.headers.set("Referrer-Policy", "unsafe-url");
  37. response.headers.set("Feature-Policy", "none");
  38. return response;
  39. } catch (e) {
  40. if (e instanceof NotFoundError || e instanceof MethodNotAllowedError) {
  41. // if a known error is thrown then serve from actual worker
  42. return await middlewareCtx.next(request, env);
  43. }
  44. // otherwise it's a real error, so throw it
  45. throw e;
  46. }
  47. };
  48. export default staticAssets;