From 5e71a8720e17b576ec12ac993f7e6b3d38fb9c8c Mon Sep 17 00:00:00 2001 From: Maik Jablonski Date: Mon, 8 Aug 2022 16:40:07 +0200 Subject: [PATCH] fix: astro preview does not serve custom 404 (4113) (#4189) * fix: astro preview does not serve custom 404 (4113) * fix: use exists instead of stat * Create thick-ducks-sparkle.md Co-authored-by: Nate Moore --- .changeset/thick-ducks-sparkle.md | 5 +++++ packages/astro/src/core/preview/index.ts | 14 +++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .changeset/thick-ducks-sparkle.md diff --git a/.changeset/thick-ducks-sparkle.md b/.changeset/thick-ducks-sparkle.md new file mode 100644 index 000000000..8c2861898 --- /dev/null +++ b/.changeset/thick-ducks-sparkle.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fix custom 404 pages when using `astro preview` (#4113) diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index 7c5b92e75..33392831c 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -3,6 +3,7 @@ import type { AddressInfo } from 'net'; import type { AstroConfig } from '../../@types/astro'; import type { LogOptions } from '../logger/core'; +import fs from 'fs'; import http from 'http'; import { performance } from 'perf_hooks'; import sirv from 'sirv'; @@ -77,7 +78,18 @@ export default async function preview( default: { // HACK: rewrite req.url so that sirv finds the file req.url = '/' + req.url?.replace(baseURL.pathname, ''); - staticFileServer(req, res, () => sendError('Not Found')); + staticFileServer(req, res, () => { + const errorPagePath = fileURLToPath(config.outDir + '/404.html'); + if (fs.existsSync(errorPagePath)) { + res.statusCode = 404; + res.setHeader('Content-Type', 'text/html;charset=utf-8'); + res.end(fs.readFileSync(errorPagePath)); + } else { + staticFileServer(req, res, () => { + sendError('Not Found'); + }); + } + }); return; } }