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; } }