Unverified Commit 51e0752f authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add generating static 500 status page (#22139)

This adds generating a static 500 status page when a `pages/500.js` file is added similar to how we handle generating static 404 pages when `pages/404.js` is present. This allows showing a customized error page when a 500 error occurs in an optimal way.  
parent 9ab98bc9
This diff is collapsed.
...@@ -189,6 +189,10 @@ export default async function exportPage({ ...@@ -189,6 +189,10 @@ export default async function exportPage({
...headerMocks, ...headerMocks,
} as unknown) as ServerResponse } as unknown) as ServerResponse
if (path === '/500' && page === '/_error') {
res.statusCode = 500
}
envConfig.setConfig({ envConfig.setConfig({
serverRuntimeConfig, serverRuntimeConfig,
publicRuntimeConfig: renderOpts.runtimeConfig, publicRuntimeConfig: renderOpts.runtimeConfig,
......
...@@ -30,7 +30,7 @@ export const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialP ...@@ -30,7 +30,7 @@ export const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialP
export const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps` export const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`
export const PAGES_404_GET_INITIAL_PROPS_ERROR = `\`pages/404\` can not have getInitialProps/getServerSideProps, https://err.sh/next.js/404-get-initial-props` export const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://err.sh/next.js/404-get-initial-props`
export const SERVER_PROPS_EXPORT_ERROR = `pages with \`getServerSideProps\` can not be exported. See more info here: https://err.sh/next.js/gssp-export` export const SERVER_PROPS_EXPORT_ERROR = `pages with \`getServerSideProps\` can not be exported. See more info here: https://err.sh/next.js/gssp-export`
......
...@@ -38,3 +38,4 @@ export const PERMANENT_REDIRECT_STATUS = 308 ...@@ -38,3 +38,4 @@ export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
export const OPTIMIZED_FONT_PROVIDERS = ['https://fonts.googleapis.com/css'] export const OPTIMIZED_FONT_PROVIDERS = ['https://fonts.googleapis.com/css']
export const STATIC_STATUS_PAGES = ['/500']
...@@ -32,6 +32,7 @@ import { ...@@ -32,6 +32,7 @@ import {
ROUTES_MANIFEST, ROUTES_MANIFEST,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
SERVER_DIRECTORY, SERVER_DIRECTORY,
STATIC_STATUS_PAGES,
TEMPORARY_REDIRECT_STATUS, TEMPORARY_REDIRECT_STATUS,
} from '../lib/constants' } from '../lib/constants'
import { import {
...@@ -1364,6 +1365,12 @@ export default class Server { ...@@ -1364,6 +1365,12 @@ export default class Server {
res.statusCode = 404 res.statusCode = 404
} }
// ensure correct status is set when visiting a status page
// directly e.g. /500
if (STATIC_STATUS_PAGES.includes(pathname)) {
res.statusCode = parseInt(pathname.substr(1), 10)
}
// handle static page // handle static page
if (typeof components.Component === 'string') { if (typeof components.Component === 'string') {
return components.Component return components.Component
...@@ -1908,9 +1915,15 @@ export default class Server { ...@@ -1908,9 +1915,15 @@ export default class Server {
result = await this.findPageComponents('/404', query) result = await this.findPageComponents('/404', query)
using404Page = result !== null using404Page = result !== null
} }
let statusPage = `/${res.statusCode}`
if (!result && STATIC_STATUS_PAGES.includes(statusPage)) {
result = await this.findPageComponents(statusPage, query)
}
if (!result) { if (!result) {
result = await this.findPageComponents('/_error', query) result = await this.findPageComponents('/_error', query)
statusPage = '/_error'
} }
if ( if (
...@@ -1928,7 +1941,7 @@ export default class Server { ...@@ -1928,7 +1941,7 @@ export default class Server {
html = await this.renderToHTMLWithComponents( html = await this.renderToHTMLWithComponents(
req, req,
res, res,
using404Page ? '/404' : '/_error', statusPage,
result!, result!,
{ {
...this.renderOpts, ...this.renderOpts,
......
...@@ -8,7 +8,7 @@ import { ...@@ -8,7 +8,7 @@ import {
GSP_NO_RETURNED_VALUE, GSP_NO_RETURNED_VALUE,
GSSP_COMPONENT_MEMBER_ERROR, GSSP_COMPONENT_MEMBER_ERROR,
GSSP_NO_RETURNED_VALUE, GSSP_NO_RETURNED_VALUE,
PAGES_404_GET_INITIAL_PROPS_ERROR, STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
SERVER_PROPS_GET_INIT_PROPS_CONFLICT, SERVER_PROPS_GET_INIT_PROPS_CONFLICT,
SERVER_PROPS_SSG_CONFLICT, SERVER_PROPS_SSG_CONFLICT,
SSG_GET_INITIAL_PROPS_CONFLICT, SSG_GET_INITIAL_PROPS_CONFLICT,
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
AMP_RENDER_TARGET, AMP_RENDER_TARGET,
SERVER_PROPS_ID, SERVER_PROPS_ID,
STATIC_PROPS_ID, STATIC_PROPS_ID,
STATIC_STATUS_PAGES,
} from '../lib/constants' } from '../lib/constants'
import { defaultHead } from '../lib/head' import { defaultHead } from '../lib/head'
import { HeadManagerContext } from '../lib/head-manager-context' import { HeadManagerContext } from '../lib/head-manager-context'
...@@ -536,7 +537,17 @@ export async function renderToHTML( ...@@ -536,7 +537,17 @@ export async function renderToHTML(
} }
if (pathname === '/404' && (hasPageGetInitialProps || getServerSideProps)) { if (pathname === '/404' && (hasPageGetInitialProps || getServerSideProps)) {
throw new Error(PAGES_404_GET_INITIAL_PROPS_ERROR) throw new Error(
`\`pages/404\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`
)
}
if (
STATIC_STATUS_PAGES.includes(pathname) &&
(hasPageGetInitialProps || getServerSideProps)
) {
throw new Error(
`\`pages${pathname}\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`
)
} }
} }
if (isAutoExport) renderOpts.autoExport = true if (isAutoExport) renderOpts.autoExport = true
......
...@@ -20,6 +20,7 @@ import { ...@@ -20,6 +20,7 @@ import {
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST, DEV_CLIENT_PAGES_MANIFEST,
STATIC_STATUS_PAGES,
} from '../next-server/lib/constants' } from '../next-server/lib/constants'
import { import {
getRouteMatcher, getRouteMatcher,
...@@ -627,6 +628,11 @@ export default class DevServer extends Server { ...@@ -627,6 +628,11 @@ export default class DevServer extends Server {
await this.devReady await this.devReady
if (res.statusCode === 404 && (await this.hasPage('/404'))) { if (res.statusCode === 404 && (await this.hasPage('/404'))) {
await this.hotReloader!.ensurePage('/404') await this.hotReloader!.ensurePage('/404')
} else if (
STATIC_STATUS_PAGES.includes(`/${res.statusCode}`) &&
(await this.hasPage(`/${res.statusCode}`))
) {
await this.hotReloader!.ensurePage(`/${res.statusCode}`)
} else { } else {
await this.hotReloader!.ensurePage('/_error') await this.hotReloader!.ensurePage('/_error')
} }
......
const page = () => {
console.log('rendered 500')
return 'custom 500 page'
}
export default page
const page = () => 'page with err'
page.getInitialProps = () => {
throw new Error('oops')
}
export default page
export default () => 'hello from index'
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import {
killApp,
findPort,
launchApp,
nextStart,
nextBuild,
renderViaHTTP,
fetchViaHTTP,
waitFor,
getPageFileFromPagesManifest,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const appDir = join(__dirname, '../')
const pages500 = join(appDir, 'pages/500.js')
const pagesApp = join(appDir, 'pages/_app.js')
const pagesError = join(appDir, 'pages/_error.js')
const nextConfig = join(appDir, 'next.config.js')
const gip500Err = /`pages\/500` can not have getInitialProps\/getServerSideProps/
let nextConfigContent
let appPort
let app
const runTests = (mode = 'server') => {
it('should use pages/500', async () => {
const html = await renderViaHTTP(appPort, '/500')
expect(html).toContain('custom 500 page')
})
it('should set correct status code with pages/500', async () => {
const res = await fetchViaHTTP(appPort, '/500')
expect(res.status).toBe(500)
})
it('should not error when visited directly', async () => {
const res = await fetchViaHTTP(appPort, '/500')
expect(res.status).toBe(500)
expect(await res.text()).toContain('custom 500 page')
})
if (mode !== 'dev') {
it('should output 500.html during build', async () => {
const page = getPageFileFromPagesManifest(appDir, '/500')
expect(page.endsWith('.html')).toBe(true)
})
it('should add /500 to pages-manifest correctly', async () => {
const manifest = await fs.readJSON(
join(appDir, '.next', mode, 'pages-manifest.json')
)
expect('/500' in manifest).toBe(true)
})
}
}
describe('500 Page Support', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests('dev')
})
describe('server mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests('server')
})
describe('serverless mode', () => {
beforeAll(async () => {
nextConfigContent = await fs.readFile(nextConfig, 'utf8')
await fs.writeFile(
nextConfig,
`
module.exports = {
target: 'serverless'
}
`
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await fs.writeFile(nextConfig, nextConfigContent)
await killApp(app)
})
runTests('serverless')
})
it('still builds 500 statically with getInitialProps in _app', async () => {
await fs.writeFile(
pagesApp,
`
import App from 'next/app'
const page = ({ Component, pageProps }) => <Component {...pageProps} />
page.getInitialProps = (ctx) => App.getInitialProps(ctx)
export default page
`
)
const { stderr, stdout: buildStdout, code } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
await fs.remove(pagesApp)
expect(stderr).not.toMatch(gip500Err)
expect(buildStdout).toContain('rendered 500')
expect(code).toBe(0)
expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(true)
let appStdout = ''
const appPort = await findPort()
const app = await nextStart(appDir, appPort, {
onStderr(msg) {
appStdout += msg || ''
},
})
await renderViaHTTP(appPort, '/err')
await killApp(app)
expect(appStdout).not.toContain('rendered 500')
})
it('builds 500 statically by default with no pages/500', async () => {
await fs.rename(pages500, `${pages500}.bak`)
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.rename(`${pages500}.bak`, pages500)
expect(stderr).not.toMatch(gip500Err)
expect(code).toBe(0)
expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(true)
})
it('builds 500 statically by default with no pages/500 and custom _error', async () => {
await fs.rename(pages500, `${pages500}.bak`)
await fs.writeFile(
pagesError,
`
function Error({ statusCode }) {
return <p>Error status: {statusCode}</p>
}
Error.getInitialProps = ({ res, err }) => {
console.error('called _error.getInitialProps')
return {
statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404
}
}
export default Error
`
)
const { stderr: buildStderr, code } = await nextBuild(appDir, [], {
stderr: true,
})
await fs.rename(`${pages500}.bak`, pages500)
await fs.remove(pagesError)
console.log(buildStderr)
expect(buildStderr).not.toMatch(gip500Err)
expect(code).toBe(0)
expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(true)
let appStderr = ''
const appPort = await findPort()
const app = await nextStart(appDir, appPort, {
onStderr(msg) {
appStderr += msg || ''
},
})
await renderViaHTTP(appPort, '/err')
await killApp(app)
expect(appStderr).toContain('called _error.getInitialProps')
})
it('shows error with getInitialProps in pages/500 build', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
page.getInitialProps = () => ({ a: 'b' })
export default page
`
)
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).toMatch(gip500Err)
expect(code).toBe(1)
})
it('shows error with getInitialProps in pages/500 dev', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
page.getInitialProps = () => ({ a: 'b' })
export default page
`
)
let stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
await renderViaHTTP(appPort, '/500')
await waitFor(1000)
await killApp(app)
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).toMatch(gip500Err)
})
it('does not show error with getStaticProps in pages/500 build', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
export const getStaticProps = () => ({ props: { a: 'b' } })
export default page
`
)
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).not.toMatch(gip500Err)
expect(code).toBe(0)
})
it('does not show error with getStaticProps in pages/500 dev', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
export const getStaticProps = () => ({ props: { a: 'b' } })
export default page
`
)
let stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
await renderViaHTTP(appPort, '/abc')
await waitFor(1000)
await killApp(app)
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).not.toMatch(gip500Err)
})
it('shows error with getServerSideProps in pages/500 build', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
export const getServerSideProps = () => ({ props: { a: 'b' } })
export default page
`
)
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).toMatch(gip500Err)
expect(code).toBe(1)
})
it('shows error with getServerSideProps in pages/500 dev', async () => {
await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page'
export const getServerSideProps = () => ({ props: { a: 'b' } })
export default page
`
)
let stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
await renderViaHTTP(appPort, '/500')
await waitFor(1000)
await killApp(app)
await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500)
expect(stderr).toMatch(gip500Err)
})
})
...@@ -2,7 +2,7 @@ import React from 'react' ...@@ -2,7 +2,7 @@ import React from 'react'
class Error extends React.Component { class Error extends React.Component {
static async getInitialProps({ req, res, err }) { static async getInitialProps({ req, res, err }) {
if (req.url !== '/404.html') { if (!req.url.startsWith('/404') && !req.url.startsWith('/500')) {
await Promise.reject(new Error('an error in error')) await Promise.reject(new Error('an error in error'))
} }
const statusCode = res ? res.statusCode : err ? err.statusCode : null const statusCode = res ? res.statusCode : err ? err.statusCode : null
......
...@@ -39,9 +39,9 @@ describe('Polyfills', () => { ...@@ -39,9 +39,9 @@ describe('Polyfills', () => {
}) })
it('should contain generated page count in output', async () => { it('should contain generated page count in output', async () => {
expect(output).toContain('Generating static pages (0/3)') expect(output).toContain('Generating static pages (0/4)')
expect(output).toContain('Generating static pages (3/3)') expect(output).toContain('Generating static pages (4/4)')
// we should only have 1 segment and the initial message logged out // we should only have 1 segment and the initial message logged out
expect(output.match(/Generating static pages/g).length).toBe(2) expect(output.match(/Generating static pages/g).length).toBe(5)
}) })
}) })
...@@ -58,8 +58,8 @@ describe('Production Usage', () => { ...@@ -58,8 +58,8 @@ describe('Production Usage', () => {
afterAll(() => stopApp(server)) afterAll(() => stopApp(server))
it('should contain generated page count in output', async () => { it('should contain generated page count in output', async () => {
expect(output).toContain('Generating static pages (0/36)') expect(output).toContain('Generating static pages (0/37)')
expect(output).toContain('Generating static pages (36/36)') expect(output).toContain('Generating static pages (37/37)')
// we should only have 4 segments and the initial message logged out // we should only have 4 segments and the initial message logged out
expect(output.match(/Generating static pages/g).length).toBe(5) expect(output.match(/Generating static pages/g).length).toBe(5)
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment