Skip to content

Commit

Permalink
Ensure cookies are attached when middleware changes the Response (#8612)
Browse files Browse the repository at this point in the history
* Ensure cookies are attached when middleware changes the Response

* fix test
  • Loading branch information
matthewp authored Sep 21, 2023
1 parent defab70 commit bcad715
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-owls-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Ensure cookies are attached when middleware changes the Response
2 changes: 1 addition & 1 deletion packages/astro/src/core/cookies/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { AstroCookies } from './cookies.js';
export { attachCookiesToResponse, getSetCookiesFromResponse } from './response.js';
export { attachCookiesToResponse, responseHasCookies, getSetCookiesFromResponse } from './response.js';
4 changes: 4 additions & 0 deletions packages/astro/src/core/cookies/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export function attachCookiesToResponse(response: Response, cookies: AstroCookie
Reflect.set(response, astroCookiesSymbol, cookies);
}

export function responseHasCookies(response: Response): boolean {
return Reflect.has(response, astroCookiesSymbol);
}

function getFromResponse(response: Response): AstroCookies | undefined {
let cookies = Reflect.get(response, astroCookiesSymbol);
if (cookies != null) {
Expand Down
12 changes: 10 additions & 2 deletions packages/astro/src/core/middleware/callMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
} from '../../@types/astro.js';
import { AstroError, AstroErrorData } from '../errors/index.js';
import type { Environment } from '../render/index.js';
import { attachCookiesToResponse, responseHasCookies } from '../cookies/index.js';

/**
* Utility function that is in charge of calling the middleware.
Expand Down Expand Up @@ -82,7 +83,7 @@ export async function callMiddleware<R>(
if (value instanceof Response === false) {
throw new AstroError(AstroErrorData.MiddlewareNotAResponse);
}
return value as R;
return ensureCookiesAttached(apiContext, value as Response);
} else {
/**
* Here we handle the case where `next` was called and returned nothing.
Expand All @@ -105,11 +106,18 @@ export async function callMiddleware<R>(
throw new AstroError(AstroErrorData.MiddlewareNotAResponse);
} else {
// Middleware did not call resolve and returned a value
return value as R;
return ensureCookiesAttached(apiContext, value as Response);
}
});
}

function ensureCookiesAttached(apiContext: APIContext, response: Response): Response {
if(apiContext.cookies !== undefined && !responseHasCookies(response)) {
attachCookiesToResponse(response, apiContext.cookies);
}
return response;
}

function isEndpointOutput(endpointResult: any): endpointResult is EndpointOutput {
return (
!(endpointResult instanceof Response) &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ const first = defineMiddleware(async (context, next) => {
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 === '/return-response-cookies') {
const response = await next();
const html = await response.text();

return new Response(html, {
status: 200,
headers: response.headers
});
} else {
if (context.url.pathname === '/') {
context.cookies.set('foo', 'bar');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
Astro.cookies.set("astro", "cookie", {
httpOnly: true,
path: "/",
sameSite: "strict",
maxAge: 1704085200,
});
---
6 changes: 6 additions & 0 deletions packages/astro/test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ describe('Middleware in DEV mode', () => {
let html = await res.text();
expect(html).to.contain('<h1>it works</h1>');
});

it('should forward cookies set in a component when the middleware returns a new response', async () => {
let res = await fixture.fetch('/return-response-cookies');
let headers = res.headers;
expect(headers.get('set-cookie')).to.not.equal(null);
});
});

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

0 comments on commit bcad715

Please sign in to comment.