forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.js
222 lines (184 loc) · 5.56 KB
/
render.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { join } from 'path'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import send from 'send'
import generateETag from 'etag'
import fresh from 'fresh'
import requireModule from './require'
import getConfig from './config'
import resolvePath from './resolve'
import { Router } from '../lib/router'
import { loadGetInitialProps } from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
import App from '../lib/app'
import ErrorDebug from '../lib/error-debug'
export async function render (req, res, pathname, query, opts) {
const html = await renderToHTML(req, res, pathname, opts)
sendHTML(req, res, html, req.method)
}
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)
}
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,
dir = process.cwd(),
dev = false,
staticMarkup = false
} = {}) {
page = page || pathname
await ensurePage(page, { dir, hotReloader })
const dist = getConfig(dir).distDir
let [Component, Document] = await Promise.all([
requireModule(join(dir, dist, 'dist', 'pages', page)),
requireModule(join(dir, dist, 'dist', 'pages', '_document'))
])
Component = Component.default || Component
Document = Document.default || Document
const ctx = { err, req, res, pathname, query }
const props = await loadGetInitialProps(Component, ctx)
// the response might be finshed on the getinitialprops call
if (res.finished) return
const renderPage = () => {
const app = createElement(App, {
Component,
props,
router: new Router(pathname, query)
})
const render = staticMarkup ? renderToStaticMarkup : renderToString
let html
let head
let errorHtml = ''
try {
html = render(app)
} finally {
head = Head.rewind() || defaultHead()
}
if (err && dev) {
errorHtml = render(createElement(ErrorDebug, { error: err }))
}
return { html, head, errorHtml }
}
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
if (res.finished) return
const doc = createElement(Document, {
__NEXT_DATA__: {
props,
pathname,
query,
buildId,
buildStats,
assetPrefix,
err: (err) ? serializeError(dev, err) : null
},
dev,
staticMarkup,
...docProps
})
return '<!DOCTYPE html>' renderToStaticMarkup(doc)
}
export async function renderScript (req, res, page, opts) {
try {
const path = join(opts.dir, '.next', 'bundles', 'pages', page)
const realPath = await resolvePath(path)
await serveStatic(req, res, realPath)
} catch (err) {
if (err.code === 'ENOENT') {
renderScriptError(req, res, page, err, {}, opts)
return
}
throw err
}
}
export async function renderScriptError (req, res, page, error, customFields, opts) {
// Asks CDNs and others to not to cache the errored page
res.setHeader('Cache-Control', 'no-store, must-revalidate')
if (error.code === 'ENOENT') {
res.setHeader('Content-Type', 'text/javascript')
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
var error = new Error('Page does not exist: ${page}')
error.statusCode = 404
return { error: error }
})
`)
return
}
res.setHeader('Content-Type', 'text/javascript')
const errorJson = {
...errorToJSON(error),
...customFields
}
res.end(`
window.__NEXT_REGISTER_PAGE('${page}', function() {
var error = ${JSON.stringify(errorJson)}
return { error: error }
})
`)
}
export function sendHTML (req, res, html, method) {
if (res.finished) return
const etag = generateETag(html)
if (fresh(req.headers, { etag })) {
res.statusCode = 304
res.end()
return
}
res.setHeader('ETag', etag)
res.setHeader('Content-Type', 'text/html')
res.setHeader('Content-Length', Buffer.byteLength(html))
res.end(method === 'HEAD' ? null : html)
}
export function sendJSON (res, obj, method) {
if (res.finished) 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) {
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
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)
}