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 <natemoo-re@users.noreply.github.com>
This commit is contained in:
Maik Jablonski 2022-08-08 16:40:07 +02:00 committed by GitHub
parent ad3d786e1f
commit 5e71a8720e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Fix custom 404 pages when using `astro preview` (#4113)

View file

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