From acc1892be64fd13968761ce3798f0bd0ff5f0fc8 Mon Sep 17 00:00:00 2001 From: Grace Kind Date: Sat, 11 Jul 2026 13:15:57 -0500 Subject: [PATCH] Send 404 for missing assets in cloudflare pages --- eleventy.config.js | 1 + functions/_middleware.js | 19 +++++++++++++++++++ src/_routes.json | 5 +++++ 3 files changed, 25 insertions(+) create mode 100644 functions/_middleware.js create mode 100644 src/_routes.json diff --git a/eleventy.config.js b/eleventy.config.js index 9d376a37..e9df8e17 100644 --- a/eleventy.config.js +++ b/eleventy.config.js @@ -23,6 +23,7 @@ export default async function (eleventyConfig) { eleventyConfig.addPassthroughCopy("src/img"); eleventyConfig.addPassthroughCopy("src/manifest.json"); eleventyConfig.addPassthroughCopy("src/_headers"); + eleventyConfig.addPassthroughCopy("src/_routes.json"); eleventyConfig.addPassthroughCopy("src/plugin-sandbox.html"); // Prevent sandbox from being treated as a template diff --git a/functions/_middleware.js b/functions/_middleware.js new file mode 100644 index 00000000..53f5ef3e --- /dev/null +++ b/functions/_middleware.js @@ -0,0 +1,19 @@ +// Send 404s for missing assets in Cloudflare pages + +const ASSET_EXTENSIONS = + /\.(m?js|css|json|md|svg|png|jpe?g|gif|webp|ico|woff2?)$/; + +export async function onRequest(context) { + const response = await context.next(); + const { pathname } = new URL(context.request.url); + const isHtml = (response.headers.get("Content-Type") || "").includes( + "text/html", + ); + if (ASSET_EXTENSIONS.test(pathname) && isHtml) { + return new Response(`Not found: ${pathname}`, { + status: 404, + headers: { "Content-Type": "text/plain; charset=utf-8" }, + }); + } + return response; +} diff --git a/src/_routes.json b/src/_routes.json new file mode 100644 index 00000000..dd5d2220 --- /dev/null +++ b/src/_routes.json @@ -0,0 +1,5 @@ +{ + "version": 1, + "include": ["/js/*", "/css/*", "/img/*"], + "exclude": [] +} -- 2.51.2