1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/render.js

254 lines
6.7 KiB
JavaScript
Raw Normal View History

2016-10-19 12:58:08 +00:00
import { join } from 'path'
2016-10-05 23:52:50 +00:00
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import send from 'send'
import generateETag from 'etag'
import fresh from 'fresh'
import requirePage from './require'
import { Router } from '../lib/router'
2018-01-31 13:12:21 +00:00
import { loadGetInitialProps, isResSent } from '../lib/utils'
import { getAvailableChunks } from './utils'
2016-12-16 18:42:40 +00:00
import Head, { defaultHead } from '../lib/head'
import ErrorDebug from '../lib/error-debug'
import { flushChunks } from '../lib/dynamic'
import { BUILD_MANIFEST, SERVER_DIRECTORY } from '../lib/constants'
import { applySourcemaps } from './lib/source-map-support'
const logger = console
2016-10-05 23:52:50 +00:00
export async function render (req, res, pathname, query, opts) {
const html = await renderToHTML(req, res, pathname, query, opts)
sendHTML(req, res, html, req.method, opts)
}
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)
sendHTML(req, res, html, req.method, opts)
}
export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
return doRender(req, res, pathname, query, { ...opts, err, page: '/_error' })
}
async function doRender (req, res, pathname, query, {
err,
page,
buildId,
hotReloader,
assetPrefix,
runtimeConfig,
availableChunks,
distDir,
dir,
2016-10-10 04:24:30 +00:00
dev = false,
staticMarkup = false,
nextExport = false
2016-10-10 04:24:30 +00:00
} = {}) {
page = page || pathname
await applySourcemaps(err)
if (hotReloader) { // In dev mode we use on demand entries to compile the page before rendering
await ensurePage(page, { dir, hotReloader })
}
const documentPath = join(distDir, SERVER_DIRECTORY, 'bundles', 'pages', '_document')
const appPath = join(distDir, SERVER_DIRECTORY, 'bundles', 'pages', '_app')
const buildManifest = require(join(distDir, BUILD_MANIFEST))
let [Component, Document, App] = await Promise.all([
requirePage(page, {distDir}),
require(documentPath),
require(appPath)
])
2016-12-16 18:42:40 +00:00
Component = Component.default || Component
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
const asPath = req.url
const ctx = { err, req, res, pathname, query, asPath }
const router = new Router(pathname, query, asPath)
const props = await loadGetInitialProps(App, {Component, router, ctx})
2016-10-05 23:52:50 +00:00
// the response might be finshed on the getinitialprops call
2018-01-31 13:12:21 +00:00
if (isResSent(res)) return
const renderPage = (enhancer = Page => Page) => {
2016-10-06 02:42:55 +00:00
const app = createElement(App, {
Component: enhancer(Component),
router,
...props
2016-10-06 02:42:55 +00:00
})
const render = staticMarkup ? renderToStaticMarkup : renderToString
let html
let head
let errorHtml = ''
2017-10-21 23:47:55 +00:00
try {
2017-10-21 23:47:55 +00:00
if (err && dev) {
errorHtml = render(createElement(ErrorDebug, { error: err }))
} else if (err) {
html = render(app)
2017-10-21 23:47:55 +00:00
} else {
html = render(app)
}
} finally {
head = Head.rewind() || defaultHead()
}
const chunks = loadChunks({ dev, distDir, availableChunks })
return { html, head, errorHtml, chunks, buildManifest }
2016-12-16 18:42:40 +00:00
}
2016-10-06 02:42:55 +00:00
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
2016-12-16 18:42:40 +00:00
2018-01-31 13:12:21 +00:00
if (isResSent(res)) return
if (!Document.prototype || !Document.prototype.isReactComponent) throw new Error('_document.js is not exporting a React element')
2016-10-05 23:52:50 +00:00
const doc = createElement(Document, {
2016-12-16 18:42:40 +00:00
__NEXT_DATA__: {
2016-10-09 09:50:41 +00:00
props,
page, // the rendered page
pathname, // the requested path
query,
buildId,
assetPrefix,
runtimeConfig,
nextExport,
err: (err) ? serializeError(dev, err) : null
2016-10-09 09:50:41 +00:00
},
2016-10-10 04:24:30 +00:00
dev,
dir,
2016-10-28 14:38:24 +00:00
staticMarkup,
buildManifest,
2016-12-16 18:42:40 +00:00
...docProps
2016-10-05 23:52:50 +00:00
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
export async function renderScriptError (req, res, page, error) {
// Asks CDNs and others to not to cache the errored page
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
if (error.code === 'ENOENT' || error.message === 'INVALID_BUILD_ID') {
res.statusCode = 404
res.end('404 - Not Found')
2017-04-04 20:35:25 +00:00
return
}
logger.error(error.stack)
res.statusCode = 500
res.end('500 - Internal Error')
}
export function sendHTML (req, res, html, method, { dev, generateEtags }) {
2018-01-31 13:12:21 +00:00
if (isResSent(res)) return
const etag = generateEtags && generateETag(html)
if (fresh(req.headers, { etag })) {
res.statusCode = 304
res.end()
return
}
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')
}
if (etag) {
res.setHeader('ETag', etag)
}
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
}
res.setHeader('Content-Length', Buffer.byteLength(html))
res.end(method === 'HEAD' ? null : html)
}
export function sendJSON (res, obj, method) {
2018-01-31 13:12:21 +00:00
if (isResSent(res)) return
const json = JSON.stringify(obj)
res.setHeader('Content-Type', 'application/json')
res.setHeader('Content-Length', Buffer.byteLength(json))
res.end(method === 'HEAD' ? null : json)
}
function errorToJSON (err) {
2016-10-19 12:41:45 +00:00
const { name, message, stack } = err
const json = { name, message, stack }
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
}
function serializeError (dev, err) {
if (dev) {
return errorToJSON(err)
}
return { message: '500 - Internal Server Error.' }
}
export function serveStatic (req, res, path) {
return new Promise((resolve, reject) => {
send(req, path)
.on('directory', () => {
// We don't allow directories to be read.
const err = new Error('No directory access')
err.code = 'ENOENT'
reject(err)
})
.on('error', reject)
.pipe(res)
.on('finish', resolve)
})
}
async function ensurePage (page, { dir, hotReloader }) {
if (page === '/_error') return
await hotReloader.ensurePage(page)
}
function loadChunks ({ dev, distDir, availableChunks }) {
const flushedChunks = flushChunks()
const response = {
names: [],
filenames: []
}
if (dev) {
availableChunks = getAvailableChunks(distDir, dev)
}
for (var chunk of flushedChunks) {
const filename = availableChunks[chunk]
if (filename) {
response.names.push(chunk)
response.filenames.push(filename)
}
}
return response
}