diff --git a/server/document.js b/server/document.js index 49eea8a5..6a27ffb2 100644 --- a/server/document.js +++ b/server/document.js @@ -84,12 +84,12 @@ export class Head extends Component { render () { const { head, styles, __NEXT_DATA__ } = this.context._documentProps - const { pathname, buildId, assetPrefix } = __NEXT_DATA__ + const { page, pathname, buildId, assetPrefix } = __NEXT_DATA__ const pagePathname = getPagePathname(pathname) return
{(head || []).map((h, i) => React.cloneElement(h, { key: h.key || i }))} - + {page !== '_error' && } {this.getPreloadDynamicChunks()} {this.getPreloadMainLinks()} @@ -173,7 +173,7 @@ export class NextScript extends Component { render () { const { staticMarkup, __NEXT_DATA__, chunks } = this.context._documentProps - const { pathname, buildId, assetPrefix } = __NEXT_DATA__ + const { page, pathname, buildId, assetPrefix } = __NEXT_DATA__ const pagePathname = getPagePathname(pathname) __NEXT_DATA__.chunks = chunks.names @@ -193,9 +193,18 @@ export class NextScript extends Component { __NEXT_REGISTER_CHUNK = function (chunkName, fn) { __NEXT_LOADED_CHUNKS__.push({ chunkName: chunkName, fn: fn }) } + + ${page === '_error' && ` + __NEXT_REGISTER_PAGE('/index', function() { + var error = new Error('Page does not exist: ${htmlescape(pathname)}') + error.statusCode = 404 + + return { error: error } + }) + `} ` }} />} - + {page !== '_error' && } {staticMarkup ? null : this.getDynamicChunks()} {staticMarkup ? null : this.getScripts()} diff --git a/server/render.js b/server/render.js index 8684c1fa..6600c1e9 100644 --- a/server/render.js +++ b/server/render.js @@ -105,7 +105,8 @@ async function doRender (req, res, pathname, query, { const doc = createElement(Document, { __NEXT_DATA__: { props, - pathname, + page, // the rendered page + pathname, // the requested path query, buildId, buildStats, diff --git a/test/integration/basic/test/rendering.js b/test/integration/basic/test/rendering.js index 08c87f76..dc07d821 100644 --- a/test/integration/basic/test/rendering.js +++ b/test/integration/basic/test/rendering.js @@ -112,6 +112,16 @@ export default function ({ app }, suiteName, render, fetch) { expect($('h2').text()).toBe('This page could not be found.') }) + test('error 404 should not have page script', async () => { + const $ = await get$('/non-existent') + $('script[src]').each((index, element) => { + const src = $(element).attr('src') + if (src.includes('/non-existent')) { + throw new Error('Page includes page script') + } + }) + }) + describe('with the HOC based router', () => { it('should navigate as expected', async () => { const $ = await get$('/nav/with-hoc')