Skip to content

Commit

Permalink
Render 404 page content when a Response with status 404 is returned…
Browse files Browse the repository at this point in the history
… from a page
  • Loading branch information
Johannes Spohr committed May 19, 2023
1 parent 1473737 commit 70c6800
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/tough-pots-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Render 404 page content when a `Response` with status 404 is returned from a page
18 changes: 9 additions & 9 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,19 +144,19 @@ export class App {
if (routeData.type === 'page') {
let response = await this.#renderPage(request, routeData, mod, defaultStatus);

// If there was a 500 error, try sending the 500 page.
if (response.status === 500) {
const fiveHundredRouteData = matchRoute('/500', this.#manifestData);
if (fiveHundredRouteData) {
mod = await this.#manifest.pageMap.get(fiveHundredRouteData.component)!();
// If there was a known error code, try sending the according page (e.g. 404.astro / 500.astro).
if (response.status === 500 || response.status === 404) {
const errorPageData = matchRoute('/' + response.status, this.#manifestData);
if (errorPageData && errorPageData.route !== routeData.route) {
mod = await this.#manifest.pageMap.get(errorPageData.component)!();
try {
let fiveHundredResponse = await this.#renderPage(
let errorResponse = await this.#renderPage(
request,
fiveHundredRouteData,
errorPageData,
mod,
500
response.status
);
return fiveHundredResponse;
return errorResponse;
} catch {}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
return new Response(null, {
status: 404,
statusText: 'Not found',
});
---
10 changes: 10 additions & 0 deletions packages/astro/test/ssr-404-500-pages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ describe('404 and 500 pages', () => {
expect($('h1').text()).to.equal('Something went horribly wrong!');
});

it('404 page returned when there is an 404 response returned from route', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/causes-404');
const response = await app.render(request);
expect(response.status).to.equal(404);
const html = await response.text();
const $ = cheerio.load(html);
expect($('h1').text()).to.equal('Something went horribly wrong!');
});

it('500 page returned when there is an error', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/causes-error');
Expand Down

0 comments on commit 70c6800

Please sign in to comment.