From 1b18e671a689b67bde20fdc7fb8cf1d6283e4ec9 Mon Sep 17 00:00:00 2001 From: Matt Kane Date: Fri, 4 Oct 2024 18:43:29 +0100 Subject: [PATCH] fix(netlify): support middleware rewrite (#413) * fix(netlify): support middleware rewrite * Changeset --- .changeset/fast-penguins-build.md | 5 +++++ packages/netlify/src/index.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 .changeset/fast-penguins-build.md diff --git a/.changeset/fast-penguins-build.md b/.changeset/fast-penguins-build.md new file mode 100644 index 000000000..afdc8786c --- /dev/null +++ b/.changeset/fast-penguins-build.md @@ -0,0 +1,5 @@ +--- +'@astrojs/netlify': patch +--- + +Fixes `context.rewrite` in edge middleware diff --git a/packages/netlify/src/index.ts b/packages/netlify/src/index.ts index feaa718bf..8ce19d51e 100644 --- a/packages/netlify/src/index.ts +++ b/packages/netlify/src/index.ts @@ -294,6 +294,25 @@ export default function netlifyIntegration( params: {} }); ctx.locals = { netlify: { context } } + // https://docs.netlify.com/edge-functions/api/#return-a-rewrite + ctx.rewrite = (target) => { + if(target instanceof Request) { + // We can only mutate headers, so if anything else is different, we need to fetch + // the target URL instead. + if(target.method !== request.method || target.body || target.url.origin !== request.url.origin) { + return fetch(target); + } + // We can't replace the headers object, so we need to delete all headers and set them again + request.headers.forEach((_value, key) => { + request.headers.delete(key); + }); + target.headers.forEach((value, key) => { + request.headers.set(key, value); + }); + return new URL(target.url); + } + return new URL(target, request.url); + }; const next = () => { const { netlify, ...otherLocals } = ctx.locals; request.headers.set("x-astro-locals", trySerializeLocals(otherLocals));