From 4426fdb98e32a03123f12708adc89501574f1614 Mon Sep 17 00:00:00 2001 From: Tim Neutkens Date: Thu, 13 Dec 2018 19:46:16 +0100 Subject: [PATCH] Make sure 404 is rendered (#5880) --- packages/next-server/server/next-server.ts | 3 ++- test/integration/production/test/index.test.js | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/next-server/server/next-server.ts b/packages/next-server/server/next-server.ts index 54887e78..9bef61a9 100644 --- a/packages/next-server/server/next-server.ts +++ b/packages/next-server/server/next-server.ts @@ -231,6 +231,7 @@ export default class Server { return html } catch (err) { if (err.code === 'ENOENT') { + res.statusCode = 404 return this.renderErrorToHTML(null, req, res, pathname, query) } else { if (!this.quiet) console.error(err) @@ -249,7 +250,7 @@ export default class Server { return this.sendHTML(req, res, html) } - public async renderErrorToHTML (err: Error|null, req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}) { + public async renderErrorToHTML (err: Error|null, req: IncomingMessage, res: ServerResponse, _pathname: string, query: ParsedUrlQuery = {}) { return renderToHTML(req, res, '/_error', query, {...this.renderOpts, err}) } diff --git a/test/integration/production/test/index.test.js b/test/integration/production/test/index.test.js index 757a7c60..36569c98 100644 --- a/test/integration/production/test/index.test.js +++ b/test/integration/production/test/index.test.js @@ -17,7 +17,7 @@ import dynamicImportTests from './dynamic' import processEnv from './process-env' import security from './security' import {BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, PAGES_MANIFEST} from 'next-server/constants' - +import cheerio from 'cheerio' const appDir = join(__dirname, '../') let appPort let server @@ -55,6 +55,16 @@ describe('Production Usage', () => { expect(res2.status).toBe(304) }) + it('should render 404 for routes that do not exist', async () => { + const url = `http://localhost:${appPort}/abcdefghijklmno` + const res = await fetch(url) + const text = await res.text() + const $html = cheerio.load(text) + expect($html('html').text()).toMatch(/404/) + expect(text).toMatch(/"statusCode":404/) + expect(res.status).toBe(404) + }) + it('should render 404 for _next routes that do not exist', async () => { const url = `http://localhost:${appPort}/_next/abcdef` const res = await fetch(url)