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.6 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'
2016-10-15 19:49:42 +00:00
import requireModule from './require'
import getConfig from './config'
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'
2016-10-05 23:52:50 +00:00
import App from '../lib/app'
import ErrorDebug from '../lib/error-debug'
import { flushChunks } from '../lib/dynamic'
import xssFilters from 'xss-filters'
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,
buildStats,
hotReloader,
assetPrefix,
availableChunks,
2016-10-10 04:24:30 +00:00
dir = process.cwd(),
dev = false,
staticMarkup = false,
nextExport = false
2016-10-10 04:24:30 +00:00
} = {}) {
page = page || pathname
await ensurePage(page, { dir, hotReloader })
const dist = getConfig(dir).distDir
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 15:40:52 +00:00
const pagePath = join(dir, dist, 'dist', 'bundles', 'pages', page)
const documentPath = join(dir, dist, 'dist', 'bundles', 'pages', '_document')
2016-12-16 18:42:40 +00:00
let [Component, Document] = await Promise.all([
Universal Webpack (#3578) * Speed up next build * Document webpack config * Speed up next build * Remove comment * Add comment * Clean up rules * Add comments * Run in parallel * Push plugins seperately * Create a new chunk for react * Don’t uglify react since it’s already uglified. Move react to commons in development * Use the minified version directly * Re-add globpattern * Move loaders into a separate variable * Add comment linking to Dan’s explanation * Remove dot * Add universal webpack * Initial dev support * Fix linting * Add changes from Arunoda's work * Made next dev works. But super slow and no HMR support. * Fix client side hot reload * Server side hmr * Only in dev * Add on-demand-entries client + hot-middleware * Add .babelrc support * Speed up on demand entries by running in parallel * Serve static generated files * Add missing config in dev * Add sass support * Add support for .map * Add cssloader config and fix .jsx support * Rename * use same defaults as css-loader. Fix linting * Add NoEmitErrorsPlugin * Add clientBootstrap * Use webpackhotmiddleware on the multi compiler * alpha.3 * Use babel 16.2.x * Fix reloading after error * Remove comment * Release 5.0.0-univeral-alpha.1 * Remove check for React 16 * Release 5.0.0-universal-alpha.2 * React hot loader v4 * Use our static file rendering machanism to serve pages. This should work well since the file path for a page is predictable. * Release 5.0.0-universal-alpha.3 * Remove optional loaders * Release 5.0.0-universal-alpha.4 * Remove clientBootstrap * Remove renderScript * Make sure pages bundles are served correctly * Remove unused import * Revert to using the same code as canary * Fix hot loader * Release 5.0.0-universal-alpha.5 * Check if externals dir exist before applying config * Add typescript support * Add support for transpiling certain packages in node_modules Thanks to @giuseppeg’s work in https://github.com/zeit/next.js/pull/3319 * Add BABEL_DISABLE_CACHE support * Make sourcemaps in production opt-in * Revert "Add support for transpiling certain packages in node_modules" This reverts commit d4b1d9babfb4b9ed4f4b12d56d52dee233e862da. In favor of a better api around this. * Support typescript through next.config.js * Remove comments * Bring back commons.js calculation * Remove unused dependencies * Move base.config.js to webpack.js * Make sure to only invalidate webpackDevMiddleware one after other. * Allow babel-loder caching by default. * Add comment about preact support * Bring back buildir replace * Remove obsolete plugin * Remove build replace, speed up build * Resolve page entries like pages/day/index.js to pages/day.js * Add componentDidCatch back * Compile to bundles * Use config.distDir everywhere * Make sure the file is an array * Remove console.log * Apply optimization to uglifyjs * Add comment pointing to source * Create entries the same way in dev and production * Remove unused and broken pagesGlobPattern * day/index.js is automatically turned into day.js at build time * Remove poweredByHeader option * Load pages with the correct path. * Release 5.0.0-universal-alpha.6 * Make sure react-dom/server can be overwritten by module-alias * Only add react-hot-loader babel plugin in dev * Release 5.0.0-universal-alpha.7 * Revert tests * Release 5.0.0-universal-alpha.10 * Make sure next/head is working properly. * Add wepack alias for 'next' back. * Make sure overriding className in next/head works * Alias react too * Add missing r * Fragment fallback has to wrap the children * Use min.js * Remove css.js * Remove wallaby.js * Release 5.0.0-universal-alpha.11 * Resolve relative to workdir instead of next * Make sure we touch the right file * Resolve next modules * Remove dotjsx removal plugins since we use webpack on the server * Revert "Resolve relative to workdir instead of next" This reverts commit a13f3e4ab565df9e2c9a3dfc8eb4009c0c2e02ed. * Externalize any locally loaded module lives outside of app dir. * Remove server aliases * Check node_modules reliably * Add symlink to next for tests * Make sure dynamic imports work locally. This is why we need it: https://github.com/webpack/webpack/blob/b545b519b2024e3f8be3041385bd326bf5d24449/lib/MainTemplate.js#L68 We need to have the finally clause in the above in __webpack_require__. webpack output option strictModuleExceptionHandling does that. * dynmaic -> dynamic * Remove webpack-node-externals * Make sure dynamic imports support SSR. * Remove css support in favor of next-css * Make sure we load path from `/` since it’s included in the path matching * Catch when ensurepage couldn’t be fulfilled for `.js.map` * Register require cache flusher for both client and server * Add comment explaining this is to facilitate hot reloading * Only load module when needed * Remove unused modules * Release 5.0.0-universal-alpha.12 * Only log the `found babel` message once * Make sure ondemand entries working correctly. Now we are just using a single instance of OnDemandEntryHandler. * Better sourcemaps * Release 5.0.0-universal-alpha.13 * Lock uglify version to 1.1.6 * Release 5.0.0-universal-alpha.14 * Fix a typo. * Introduce multi-zones support for mircofrontends * Add section on css
2018-01-30 15:40:52 +00:00
requireModule(pagePath),
requireModule(documentPath)
2016-12-16 18:42:40 +00:00
])
Component = Component.default || Component
Document = Document.default || Document
const asPath = req.url
const ctx = { err, req, res, pathname, query, asPath }
2017-04-06 05:31:44 +00:00
const props = await loadGetInitialProps(Component, 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),
2016-10-06 02:42:55 +00:00
props,
router: new Router(pathname, query, asPath)
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) {
errorHtml = render(app)
} else {
html = render(app)
}
} finally {
head = Head.rewind() || defaultHead()
}
const chunks = loadChunks({ dev, dir, dist, availableChunks })
return { html, head, errorHtml, chunks }
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,
pathname,
query,
buildId,
buildStats,
assetPrefix,
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,
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, customFields, { dev }) {
// Asks CDNs and others to not to cache the errored page
res.setHeader('Cache-Control', 'no-store, must-revalidate')
// prevent XSS attacks by filtering the page before printing it.
page = xssFilters.uriInSingleQuotedAttr(page)
res.setHeader('Content-Type', 'text/javascript')
2017-04-04 20:35:25 +00:00
if (error.code === 'ENOENT') {
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
2017-04-12 16:12:04 +00:00
var error = new Error('Page does not exist: ${page}')
2017-04-05 11:43:34 +00:00
error.statusCode = 404
return { error: error }
})
2017-04-04 20:35:25 +00:00
`)
return
}
const errorJson = {
...serializeError(dev, error),
...customFields
}
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
2017-04-05 11:43:34 +00:00
var error = ${JSON.stringify(errorJson)}
return { error: error }
})
`)
}
export function sendHTML (req, res, html, method, { dev }) {
2018-01-31 13:12:21 +00:00
if (isResSent(res)) return
const etag = 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')
}
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 (!hotReloader) return
if (page === '_error' || page === '_document') return
await hotReloader.ensurePage(page)
}
function loadChunks ({ dev, dir, dist, availableChunks }) {
const flushedChunks = flushChunks()
const response = {
names: [],
filenames: []
}
if (dev) {
availableChunks = getAvailableChunks(dir, dist)
}
for (var chunk of flushedChunks) {
const filename = availableChunks[chunk]
if (filename) {
response.names.push(chunk)
response.filenames.push(filename)
}
}
return response
}