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(app): provide adapter locals to error pages #10427

Merged
merged 3 commits into from
Mar 13, 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/thin-deers-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Fixes an issue where error pages did not have access to the `Astro.locals` fields provided by the adapter.
10 changes: 7 additions & 3 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface RenderOptions {
}

export interface RenderErrorOptions {
locals?: App.Locals,
routeData?: RouteData;
response?: Response;
status: 404 | 500;
Expand Down Expand Up @@ -295,7 +296,7 @@ export class App {
routeData = this.match(request);
}
if (!routeData) {
return this.#renderError(request, { status: 404 });
return this.#renderError(request, { locals, status: 404 });
}
const pathname = this.#getPathnameFromRequest(request);
const defaultStatus = this.#getDefaultStatusCode(routeData, pathname);
Expand All @@ -314,14 +315,15 @@ export class App {
response = await renderContext.render(await mod.page());
} catch (err: any) {
this.#logger.error(null, err.stack || err.message || String(err));
return this.#renderError(request, { status: 500 });
return this.#renderError(request, { locals, status: 500 });
}

if (
REROUTABLE_STATUS_CODES.includes(response.status) &&
response.headers.get(REROUTE_DIRECTIVE_HEADER) !== 'no'
) {
return this.#renderError(request, {
locals,
response,
status: response.status as 404 | 500,
});
Expand Down Expand Up @@ -374,7 +376,7 @@ export class App {
*/
async #renderError(
request: Request,
{ status, response: originalResponse, skipMiddleware = false }: RenderErrorOptions
{ locals, status, response: originalResponse, skipMiddleware = false }: RenderErrorOptions
): Promise<Response> {
const errorRoutePath = `/${status}${this.#manifest.trailingSlash === 'always' ? '/' : ''}`;
const errorRouteData = matchRoute(errorRoutePath, this.#manifestData);
Expand All @@ -397,6 +399,7 @@ export class App {
const mod = await this.#getModuleForRoute(errorRouteData);
try {
const renderContext = RenderContext.create({
locals,
pipeline: this.#pipeline,
middleware: skipMiddleware ? (_, next) => next() : undefined,
pathname: this.#getPathnameFromRequest(request),
Expand All @@ -410,6 +413,7 @@ export class App {
// Middleware may be the cause of the error, so we try rendering 404/500.astro without it.
if (skipMiddleware === false) {
return this.#renderError(request, {
locals,
status,
response: originalResponse,
skipMiddleware: true,
Expand Down
4 changes: 4 additions & 0 deletions packages/astro/test/fixtures/ssr-locals/src/pages/404.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
const { foo } = Astro.locals;
---
<h1 id="foo">{ foo }</h1>
4 changes: 4 additions & 0 deletions packages/astro/test/fixtures/ssr-locals/src/pages/500.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
const { foo } = Astro.locals;
---
<h1 id="foo">{ foo }</h1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
throw new Error
---
27 changes: 25 additions & 2 deletions packages/astro/test/ssr-locals.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { loadFixture } from './test-utils.js';
describe('SSR Astro.locals from server', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
/** @type {import('./test-utils.js').App} */
let app;

before(async () => {
fixture = await loadFixture({
Expand All @@ -15,10 +17,10 @@ describe('SSR Astro.locals from server', () => {
adapter: testAdapter(),
});
await fixture.build();
app = await fixture.loadTestAdapterApp();
});

it('Can access Astro.locals in page', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/foo');
const locals = { foo: 'bar' };
const response = await app.render(request, { locals });
Expand All @@ -29,7 +31,6 @@ describe('SSR Astro.locals from server', () => {
});

it('Can access Astro.locals in api context', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/api');
const locals = { foo: 'bar' };
const response = await app.render(request, undefined, locals);
Expand All @@ -38,4 +39,26 @@ describe('SSR Astro.locals from server', () => {

assert.equal(body.foo, 'bar');
});

it('404.astro can access locals provided to app.render()', async () => {
const request = new Request('http://example.com/slkfnasf');
const locals = { foo: 'par' };
const response = await app.render(request, { locals });
assert.equal(response.status, 404);

const html = await response.text();
const $ = cheerio.load(html);
assert.equal($('#foo').text(), 'par');
});

it('500.astro can access locals provided to app.render()', async () => {
const request = new Request('http://example.com/go-to-error-page');
const locals = { foo: 'par' };
const response = await app.render(request, { locals });
assert.equal(response.status, 500);

const html = await response.text();
const $ = cheerio.load(html);
assert.equal($('#foo').text(), 'par');
});
});
Loading