Skip to content

Commit

Permalink
fix(netlify): support middleware rewrite (#413)
Browse files Browse the repository at this point in the history
* fix(netlify): support middleware rewrite

* Changeset
  • Loading branch information
ascorbic authored Oct 4, 2024
1 parent dd6a7c9 commit 1b18e67
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/fast-penguins-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/netlify': patch
---

Fixes `context.rewrite` in edge middleware
19 changes: 19 additions & 0 deletions packages/netlify/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 1b18e67

Please sign in to comment.