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": [] +}