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

Render 404 page content for existing pages with 404 Response #7143

Merged
merged 1 commit into from May 22, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tough-pots-visit.md
@@ -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
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
@@ -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
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