Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(netlify): support middleware rewrite #413

Merged
merged 2 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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