Compare commits

...

1 commit

Author SHA1 Message Date
Emanuele Stoppa
25f448b68e fix: cookies in redirect 2023-08-23 15:01:24 +01:00
5 changed files with 19 additions and 4 deletions

View file

@ -48,12 +48,14 @@ export function createAPIContext({
generator: `Astro v${ASTRO_VERSION}`,
props,
redirect(path, status) {
return new Response(null, {
const response = new Response(null, {
status: status || 302,
headers: {
Location: path,
},
});
attachCookiesToResponse(response, context.cookies);
return response;
},
ResponseWithEncoding,
url: new URL(request.url),

View file

@ -24,12 +24,14 @@ export type RenderPage = {
export async function renderPage({ mod, renderContext, env, cookies }: RenderPage) {
if (routeIsRedirect(renderContext.route)) {
return new Response(null, {
const response = new Response(null, {
status: redirectRouteStatus(renderContext.route, renderContext.request.method),
headers: {
location: redirectRouteGenerate(renderContext.route, renderContext.params),
},
});
attachToResponse(response, cookies);
return response;
}
// Validate the page component before rendering the page

View file

@ -18,14 +18,14 @@ const first = defineMiddleware(async (context, next) => {
return new Response(JSON.stringify(object), {
headers: response.headers,
});
} else if(context.url.pathname === '/clone') {
} 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 === '/') {
if (context.url.pathname === '/') {
context.cookies.set('foo', 'bar');
}
@ -38,6 +38,7 @@ const second = defineMiddleware(async (context, next) => {
if (context.request.url.includes('/second')) {
context.locals.name = 'second';
} else if (context.request.url.includes('/redirect')) {
context.cookies.set('redirect', 'cookie redirect set');
return context.redirect('/', 302);
}
return await next();

View file

@ -1,5 +1,7 @@
---
const data = Astro.locals;
const redirect = Astro.cookies.get("redirect");
console.log(redirect);
---
<html>
@ -10,5 +12,6 @@ const data = Astro.locals;
<span>Index</span>
<p>{data?.name}</p>
<p>{redirect.value}</p>
</body>
</html>

View file

@ -79,6 +79,13 @@ describe('Middleware in DEV mode', () => {
let html = await res.text();
expect(html).to.contain('<h1>it works</h1>');
});
it('cookies should be preserved when calling a redirect', async () => {
let res = await fixture.fetch('/redirect');
let html = await res.text();
console.log(res.headers.get('set-cookie'));
expect(html).to.contain('<p>cookie redirect set</p>');
});
});
describe('Middleware in PROD mode, SSG', () => {