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));