Skip to content

Commit

Permalink
Fixes Response not being cloneable by middleware (#7623)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewp authored Jul 11, 2023
1 parent f0666b9 commit 86e19c7
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/tasty-beans-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Allow our Response wrapper to be cloneable
8 changes: 8 additions & 0 deletions packages/astro/src/runtime/server/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ function createResponseClass() {
}
return super.arrayBuffer();
}

clone() {
return new StreamingCompatibleResponse!(this.#body, {
status: this.status,
statusText: this.statusText,
headers: this.headers
});
}
};

return StreamingCompatibleResponse;
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/fixtures/middleware-dev/src/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const first = defineMiddleware(async (context, next) => {
return new Response(JSON.stringify(object), {
headers: response.headers,
});
} else if(context.url.pathname === '/clone') {
const response = await next();
const newResponse = response.clone();
const /** @type {string} */ html = await newResponse.text();
const newhtml = html.replace('<h1>testing</h1>', '<h1>it works</h1>');
return new Response(newhtml, { status: 200, headers: response.headers });
} else {
if(context.url.pathname === '/') {
context.cookies.set('foo', 'bar');
Expand Down
12 changes: 12 additions & 0 deletions packages/astro/test/fixtures/middleware-dev/src/pages/clone.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
---

<html>
<head>
<title>Testing</title>
</head>
<body>
<h1>testing</h1>
</body>
</html>
6 changes: 6 additions & 0 deletions packages/astro/test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ describe('Middleware in DEV mode', () => {
let res = await fixture.fetch('/');
expect(res.headers.get('set-cookie')).to.equal('foo=bar');
});

it('should be able to clone the response', async () => {
let res = await fixture.fetch('/clone');
let html = await res.text();
expect(html).to.contain('<h1>it works</h1>');
});
});

describe('Middleware in PROD mode, SSG', () => {
Expand Down

0 comments on commit 86e19c7

Please sign in to comment.