2016-10-19 12:58:08 +00:00
|
|
|
import { join } from 'path'
|
2018-07-24 09:24:40 +00:00
|
|
|
import React from 'react'
|
2016-10-05 23:52:50 +00:00
|
|
|
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
|
2016-12-31 12:46:23 +00:00
|
|
|
import send from 'send'
|
2017-04-18 15:45:42 +00:00
|
|
|
import generateETag from 'etag'
|
|
|
|
import fresh from 'fresh'
|
2018-07-24 09:24:40 +00:00
|
|
|
import requirePage, {normalizePagePath} from './require'
|
2016-12-20 17:27:43 +00:00
|
|
|
import { Router } from '../lib/router'
|
2018-01-31 13:12:21 +00:00
|
|
|
import { loadGetInitialProps, isResSent } from '../lib/utils'
|
2016-12-16 18:42:40 +00:00
|
|
|
import Head, { defaultHead } from '../lib/head'
|
2017-04-01 21:03:40 +00:00
|
|
|
import ErrorDebug from '../lib/error-debug'
|
2018-07-24 09:24:40 +00:00
|
|
|
import Loadable from 'react-loadable'
|
2018-07-25 11:45:42 +00:00
|
|
|
import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH } from '../lib/constants'
|
2018-07-24 09:24:40 +00:00
|
|
|
|
|
|
|
// Based on https://github.com/jamiebuilds/react-loadable/pull/132
|
2018-07-25 11:45:42 +00:00
|
|
|
function getDynamicImportBundles (manifest, moduleIds) {
|
2018-07-24 09:24:40 +00:00
|
|
|
return moduleIds.reduce((bundles, moduleId) => {
|
|
|
|
if (typeof manifest[moduleId] === 'undefined') {
|
|
|
|
return bundles
|
|
|
|
}
|
|
|
|
|
|
|
|
return bundles.concat(manifest[moduleId])
|
|
|
|
}, [])
|
|
|
|
}
|
2018-02-21 17:41:25 +00:00
|
|
|
|
|
|
|
const logger = console
|
2016-10-05 23:52:50 +00:00
|
|
|
|
2016-12-16 20:33:08 +00:00
|
|
|
export async function render (req, res, pathname, query, opts) {
|
2017-06-23 23:08:05 +00:00
|
|
|
const html = await renderToHTML(req, res, pathname, query, opts)
|
2017-05-25 16:28:08 +00:00
|
|
|
sendHTML(req, res, html, req.method, opts)
|
2016-12-16 20:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function renderToHTML (req, res, pathname, query, opts) {
|
|
|
|
return doRender(req, res, pathname, query, opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function renderError (err, req, res, pathname, query, opts) {
|
|
|
|
const html = await renderErrorToHTML(err, req, res, query, opts)
|
2017-05-25 16:28:08 +00:00
|
|
|
sendHTML(req, res, html, req.method, opts)
|
2016-12-16 20:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
|
2018-02-13 15:13:22 +00:00
|
|
|
return doRender(req, res, pathname, query, { ...opts, err, page: '/_error' })
|
2016-12-16 20:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function doRender (req, res, pathname, query, {
|
|
|
|
err,
|
|
|
|
page,
|
2017-01-11 20:16:18 +00:00
|
|
|
buildId,
|
2017-02-26 19:45:16 +00:00
|
|
|
hotReloader,
|
2017-04-18 04:18:43 +00:00
|
|
|
assetPrefix,
|
2018-02-26 11:03:27 +00:00
|
|
|
runtimeConfig,
|
2018-06-04 13:45:39 +00:00
|
|
|
distDir,
|
|
|
|
dir,
|
2016-10-10 04:24:30 +00:00
|
|
|
dev = false,
|
2017-05-09 01:20:50 +00:00
|
|
|
staticMarkup = false,
|
2018-07-24 09:24:40 +00:00
|
|
|
nextExport
|
2016-10-10 04:24:30 +00:00
|
|
|
} = {}) {
|
2016-12-16 20:33:08 +00:00
|
|
|
page = page || pathname
|
2017-02-26 19:45:16 +00:00
|
|
|
|
2018-02-13 13:27:52 +00:00
|
|
|
if (hotReloader) { // In dev mode we use on demand entries to compile the page before rendering
|
|
|
|
await ensurePage(page, { dir, hotReloader })
|
|
|
|
}
|
2017-02-26 19:45:16 +00:00
|
|
|
|
2018-07-25 11:45:42 +00:00
|
|
|
const documentPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_document')
|
|
|
|
const appPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_app')
|
2018-07-24 09:24:40 +00:00
|
|
|
let [buildManifest, reactLoadableManifest, Component, Document, App] = await Promise.all([
|
|
|
|
require(join(distDir, BUILD_MANIFEST)),
|
|
|
|
require(join(distDir, REACT_LOADABLE_MANIFEST)),
|
2018-06-04 13:45:39 +00:00
|
|
|
requirePage(page, {distDir}),
|
2018-04-12 08:33:22 +00:00
|
|
|
require(documentPath),
|
|
|
|
require(appPath)
|
2018-03-09 16:14:30 +00:00
|
|
|
])
|
2018-04-12 08:33:22 +00:00
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
await Loadable.preloadAll() // Make sure all dynamic imports are loaded
|
|
|
|
|
2016-12-16 18:42:40 +00:00
|
|
|
Component = Component.default || Component
|
2018-04-12 08:33:22 +00:00
|
|
|
|
|
|
|
if (typeof Component !== 'function') {
|
|
|
|
throw new Error(`The default export is not a React Component in page: "${pathname}"`)
|
|
|
|
}
|
|
|
|
|
|
|
|
App = App.default || App
|
2016-12-16 18:42:40 +00:00
|
|
|
Document = Document.default || Document
|
2017-05-03 16:40:09 +00:00
|
|
|
const asPath = req.url
|
|
|
|
const ctx = { err, req, res, pathname, query, asPath }
|
2018-04-12 08:33:22 +00:00
|
|
|
const router = new Router(pathname, query, asPath)
|
|
|
|
const props = await loadGetInitialProps(App, {Component, router, ctx})
|
2018-07-24 09:24:40 +00:00
|
|
|
const files = [
|
|
|
|
...new Set([
|
|
|
|
...buildManifest.pages[normalizePagePath(page)],
|
|
|
|
...buildManifest.pages[normalizePagePath('/_app')],
|
|
|
|
...buildManifest.pages[normalizePagePath('/_error')]
|
|
|
|
])
|
|
|
|
]
|
2016-10-05 23:52:50 +00:00
|
|
|
|
2016-12-16 20:33:08 +00:00
|
|
|
// the response might be finshed on the getinitialprops call
|
2018-01-31 13:12:21 +00:00
|
|
|
if (isResSent(res)) return
|
2016-12-16 20:33:08 +00:00
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
let reactLoadableModules = []
|
2018-07-13 09:22:45 +00:00
|
|
|
const renderPage = (options = Page => Page) => {
|
|
|
|
let EnhancedApp = App
|
|
|
|
let EnhancedComponent = Component
|
|
|
|
|
|
|
|
// For backwards compatibility
|
|
|
|
if (typeof options === 'function') {
|
|
|
|
EnhancedComponent = options(Component)
|
|
|
|
} else if (typeof options === 'object') {
|
|
|
|
if (options.enhanceApp) {
|
|
|
|
EnhancedApp = options.enhanceApp(App)
|
|
|
|
}
|
|
|
|
if (options.enhanceComponent) {
|
|
|
|
EnhancedComponent = options.enhanceComponent(Component)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
const app = <Loadable.Capture report={moduleName => reactLoadableModules.push(moduleName)}>
|
|
|
|
<EnhancedApp {...{
|
|
|
|
Component: EnhancedComponent,
|
|
|
|
router,
|
|
|
|
...props
|
|
|
|
}} />
|
|
|
|
</Loadable.Capture>
|
2016-12-20 17:27:43 +00:00
|
|
|
|
2016-12-21 15:57:25 +00:00
|
|
|
const render = staticMarkup ? renderToStaticMarkup : renderToString
|
|
|
|
|
|
|
|
let html
|
|
|
|
let head
|
2017-04-01 21:03:40 +00:00
|
|
|
let errorHtml = ''
|
2017-10-21 23:47:55 +00:00
|
|
|
|
2016-12-21 15:57:25 +00:00
|
|
|
try {
|
2017-10-21 23:47:55 +00:00
|
|
|
if (err && dev) {
|
2018-07-24 09:24:40 +00:00
|
|
|
errorHtml = render(<ErrorDebug error={err} />)
|
2017-10-21 23:47:55 +00:00
|
|
|
} else if (err) {
|
2018-04-18 16:18:06 +00:00
|
|
|
html = render(app)
|
2017-10-21 23:47:55 +00:00
|
|
|
} else {
|
|
|
|
html = render(app)
|
|
|
|
}
|
2016-12-21 15:57:25 +00:00
|
|
|
} finally {
|
|
|
|
head = Head.rewind() || defaultHead()
|
|
|
|
}
|
2017-04-01 21:03:40 +00:00
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
return { html, head, errorHtml, buildManifest }
|
2016-12-16 18:42:40 +00:00
|
|
|
}
|
2016-10-06 02:42:55 +00:00
|
|
|
|
2017-01-20 19:33:46 +00:00
|
|
|
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
|
2018-07-25 11:45:42 +00:00
|
|
|
const dynamicImports = getDynamicImportBundles(reactLoadableManifest, reactLoadableModules)
|
2016-12-16 18:42:40 +00:00
|
|
|
|
2018-01-31 13:12:21 +00:00
|
|
|
if (isResSent(res)) return
|
2017-01-26 11:06:50 +00:00
|
|
|
|
2018-06-24 15:10:24 +00:00
|
|
|
if (!Document.prototype || !Document.prototype.isReactComponent) throw new Error('_document.js is not exporting a React component')
|
2018-07-24 09:24:40 +00:00
|
|
|
const doc = <Document {...{
|
2016-12-16 18:42:40 +00:00
|
|
|
__NEXT_DATA__: {
|
2018-07-24 09:24:40 +00:00
|
|
|
// Used in development to replace paths for react-error-overlay
|
|
|
|
distDir: dev ? distDir : undefined,
|
|
|
|
props, // The result of getInitialProps
|
|
|
|
page, // The rendered page
|
|
|
|
pathname, // The requested path
|
|
|
|
query, // querystring parsed / passed by the user
|
|
|
|
buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
|
|
|
|
assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
|
|
|
|
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
|
|
|
|
nextExport, // If this is a page exported by `next export`
|
|
|
|
err: (err) ? serializeError(dev, err) : undefined // Error if one happened, otherwise don't sent in the resulting HTML
|
2016-10-09 09:50:41 +00:00
|
|
|
},
|
2016-10-10 04:24:30 +00:00
|
|
|
dev,
|
2017-05-08 02:36:11 +00:00
|
|
|
dir,
|
2016-10-28 14:38:24 +00:00
|
|
|
staticMarkup,
|
2018-04-12 07:47:42 +00:00
|
|
|
buildManifest,
|
2018-07-24 09:24:40 +00:00
|
|
|
files,
|
|
|
|
dynamicImports,
|
|
|
|
assetPrefix, // We always pass assetPrefix as a top level property since _document needs it to render, even though the client side might not need it
|
2016-12-16 18:42:40 +00:00
|
|
|
...docProps
|
2018-07-24 09:24:40 +00:00
|
|
|
}} />
|
2016-10-05 23:52:50 +00:00
|
|
|
|
|
|
|
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
|
|
|
|
}
|
|
|
|
|
2018-02-21 17:41:25 +00:00
|
|
|
export async function renderScriptError (req, res, page, error) {
|
2017-04-24 20:48:34 +00:00
|
|
|
// Asks CDNs and others to not to cache the errored page
|
2018-05-06 20:57:27 +00:00
|
|
|
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
|
2017-04-24 20:48:34 +00:00
|
|
|
|
2018-03-31 07:01:46 +00:00
|
|
|
if (error.code === 'ENOENT' || error.message === 'INVALID_BUILD_ID') {
|
2018-02-21 17:41:25 +00:00
|
|
|
res.statusCode = 404
|
|
|
|
res.end('404 - Not Found')
|
2017-04-04 20:35:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-02-21 17:41:25 +00:00
|
|
|
logger.error(error.stack)
|
|
|
|
res.statusCode = 500
|
|
|
|
res.end('500 - Internal Error')
|
2017-04-04 19:55:56 +00:00
|
|
|
}
|
|
|
|
|
2018-03-13 13:18:59 +00:00
|
|
|
export function sendHTML (req, res, html, method, { dev, generateEtags }) {
|
2018-01-31 13:12:21 +00:00
|
|
|
if (isResSent(res)) return
|
2018-03-13 13:18:59 +00:00
|
|
|
const etag = generateEtags && generateETag(html)
|
2016-12-30 19:55:20 +00:00
|
|
|
|
2017-04-18 15:45:42 +00:00
|
|
|
if (fresh(req.headers, { etag })) {
|
|
|
|
res.statusCode = 304
|
|
|
|
res.end()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-25 16:28:08 +00:00
|
|
|
if (dev) {
|
|
|
|
// In dev, we should not cache pages for any reason.
|
|
|
|
// That's why we do this.
|
|
|
|
res.setHeader('Cache-Control', 'no-store, must-revalidate')
|
|
|
|
}
|
|
|
|
|
2018-03-13 13:18:59 +00:00
|
|
|
if (etag) {
|
|
|
|
res.setHeader('ETag', etag)
|
|
|
|
}
|
|
|
|
|
2017-11-05 19:17:03 +00:00
|
|
|
if (!res.getHeader('Content-Type')) {
|
2017-12-06 00:00:58 +00:00
|
|
|
res.setHeader('Content-Type', 'text/html; charset=utf-8')
|
2017-11-05 19:17:03 +00:00
|
|
|
}
|
2016-12-16 20:33:08 +00:00
|
|
|
res.setHeader('Content-Length', Buffer.byteLength(html))
|
2017-01-12 15:38:43 +00:00
|
|
|
res.end(method === 'HEAD' ? null : html)
|
2016-12-16 20:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function errorToJSON (err) {
|
2016-10-19 12:41:45 +00:00
|
|
|
const { name, message, stack } = err
|
|
|
|
const json = { name, message, stack }
|
|
|
|
|
2017-03-22 23:13:23 +00:00
|
|
|
if (err.module) {
|
|
|
|
// rawRequest contains the filename of the module which has the error.
|
|
|
|
const { rawRequest } = err.module
|
2016-10-19 12:41:45 +00:00
|
|
|
json.module = { rawRequest }
|
|
|
|
}
|
|
|
|
|
|
|
|
return json
|
|
|
|
}
|
2016-12-31 12:46:23 +00:00
|
|
|
|
2017-04-25 04:15:58 +00:00
|
|
|
function serializeError (dev, err) {
|
|
|
|
if (dev) {
|
|
|
|
return errorToJSON(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return { message: '500 - Internal Server Error.' }
|
|
|
|
}
|
|
|
|
|
2016-12-31 12:46:23 +00:00
|
|
|
export function serveStatic (req, res, path) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
send(req, path)
|
2018-03-27 18:11:03 +00:00
|
|
|
.on('directory', () => {
|
2017-02-08 00:13:25 +00:00
|
|
|
// We don't allow directories to be read.
|
2018-03-27 18:11:03 +00:00
|
|
|
const err = new Error('No directory access')
|
|
|
|
err.code = 'ENOENT'
|
|
|
|
reject(err)
|
|
|
|
})
|
|
|
|
.on('error', reject)
|
|
|
|
.pipe(res)
|
|
|
|
.on('finish', resolve)
|
2016-12-31 12:46:23 +00:00
|
|
|
})
|
|
|
|
}
|
2017-02-26 19:45:16 +00:00
|
|
|
|
|
|
|
async function ensurePage (page, { dir, hotReloader }) {
|
2018-02-13 15:13:22 +00:00
|
|
|
if (page === '/_error') return
|
2017-02-26 19:45:16 +00:00
|
|
|
|
|
|
|
await hotReloader.ensurePage(page)
|
|
|
|
}
|