2019-05-27 20:20:33 +02:00
|
|
|
import fs from 'fs'
|
2019-03-01 20:51:13 +01:00
|
|
|
import { IncomingMessage, ServerResponse } from 'http'
|
2019-05-27 20:20:33 +02:00
|
|
|
import { join, resolve, sep } from 'path'
|
2018-12-09 22:46:45 +01:00
|
|
|
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
|
2019-05-27 20:20:33 +02:00
|
|
|
import { parse as parseUrl, UrlWithParsedQuery } from 'url'
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
import {
|
|
|
|
BUILD_ID_FILE,
|
2019-05-27 20:20:33 +02:00
|
|
|
BUILD_MANIFEST,
|
2019-05-03 18:57:47 +02:00
|
|
|
CLIENT_PUBLIC_FILES_PATH,
|
2019-03-01 20:51:13 +01:00
|
|
|
CLIENT_STATIC_FILES_PATH,
|
|
|
|
CLIENT_STATIC_FILES_RUNTIME,
|
2019-05-03 18:57:47 +02:00
|
|
|
PAGES_MANIFEST,
|
2019-05-27 20:20:33 +02:00
|
|
|
PHASE_PRODUCTION_SERVER,
|
|
|
|
SERVER_DIRECTORY,
|
2019-06-10 02:18:38 +02:00
|
|
|
SERVERLESS_DIRECTORY,
|
2019-04-24 16:47:50 +02:00
|
|
|
} from '../lib/constants'
|
2019-05-31 11:27:56 +02:00
|
|
|
import {
|
|
|
|
getRouteMatcher,
|
|
|
|
getRouteRegex,
|
|
|
|
getSortedRoutes,
|
|
|
|
} from '../lib/router/utils'
|
2018-02-26 12:03:27 +01:00
|
|
|
import * as envConfig from '../lib/runtime-config'
|
2019-06-05 13:22:09 +02:00
|
|
|
import { NextApiRequest, NextApiResponse } from '../lib/utils'
|
|
|
|
import { parse as parseCookies } from 'cookie'
|
|
|
|
import {
|
|
|
|
parseQuery,
|
|
|
|
sendJson,
|
|
|
|
sendData,
|
|
|
|
parseBody,
|
|
|
|
sendError,
|
|
|
|
ApiError,
|
|
|
|
sendStatusCode,
|
|
|
|
} from './api-utils'
|
2019-05-27 20:20:33 +02:00
|
|
|
import loadConfig from './config'
|
|
|
|
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
|
2019-05-26 23:22:43 +02:00
|
|
|
import {
|
|
|
|
interopDefault,
|
2019-05-27 20:20:33 +02:00
|
|
|
loadComponents,
|
2019-05-26 23:22:43 +02:00
|
|
|
LoadComponentsReturnType,
|
|
|
|
} from './load-components'
|
2019-05-27 20:20:33 +02:00
|
|
|
import { renderToHTML } from './render'
|
2019-05-26 23:22:43 +02:00
|
|
|
import { getPagePath } from './require'
|
2019-05-27 20:20:33 +02:00
|
|
|
import Router, { route, Route, RouteMatch } from './router'
|
|
|
|
import { sendHTML } from './send-html'
|
|
|
|
import { serveStatic } from './serve-static'
|
|
|
|
import { isBlockedPage, isInternalUrl } from './utils'
|
2018-12-09 22:46:45 +01:00
|
|
|
|
|
|
|
type NextConfig = any
|
|
|
|
|
2019-04-24 16:47:50 +02:00
|
|
|
export type ServerConstructor = {
|
2019-03-01 20:51:13 +01:00
|
|
|
dir?: string
|
|
|
|
staticMarkup?: boolean
|
|
|
|
quiet?: boolean
|
2019-05-29 13:57:26 +02:00
|
|
|
conf?: NextConfig
|
2018-12-09 22:46:45 +01:00
|
|
|
}
|
2017-04-07 19:58:35 +02:00
|
|
|
|
2016-10-06 01:52:50 +02:00
|
|
|
export default class Server {
|
2018-12-09 22:46:45 +01:00
|
|
|
dir: string
|
|
|
|
quiet: boolean
|
|
|
|
nextConfig: NextConfig
|
|
|
|
distDir: string
|
2019-05-03 18:57:47 +02:00
|
|
|
publicDir: string
|
2019-05-27 20:20:33 +02:00
|
|
|
buildManifest: string
|
2018-12-09 22:46:45 +01:00
|
|
|
buildId: string
|
|
|
|
renderOpts: {
|
2019-04-15 09:48:14 +02:00
|
|
|
poweredByHeader: boolean
|
2019-04-02 16:09:34 +02:00
|
|
|
ampBindInitData: boolean
|
2019-03-01 20:51:13 +01:00
|
|
|
staticMarkup: boolean
|
|
|
|
buildId: string
|
|
|
|
generateEtags: boolean
|
|
|
|
runtimeConfig?: { [key: string]: any }
|
2019-05-29 13:57:26 +02:00
|
|
|
assetPrefix?: string
|
|
|
|
canonicalBase: string
|
2019-05-26 23:22:43 +02:00
|
|
|
autoExport: boolean
|
2019-05-29 13:57:26 +02:00
|
|
|
dev?: boolean
|
2018-12-09 22:46:45 +01:00
|
|
|
}
|
|
|
|
router: Router
|
2019-05-27 20:20:33 +02:00
|
|
|
private dynamicRoutes?: Array<{ page: string; match: RouteMatch }>
|
2018-12-09 22:46:45 +01:00
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public constructor({
|
|
|
|
dir = '.',
|
|
|
|
staticMarkup = false,
|
|
|
|
quiet = false,
|
|
|
|
conf = null,
|
|
|
|
}: ServerConstructor = {}) {
|
2016-10-06 13:05:52 +02:00
|
|
|
this.dir = resolve(dir)
|
2016-12-16 21:33:08 +01:00
|
|
|
this.quiet = quiet
|
2018-09-28 14:05:23 +02:00
|
|
|
const phase = this.currentPhase()
|
2018-06-04 11:38:46 +02:00
|
|
|
this.nextConfig = loadConfig(phase, this.dir, conf)
|
2018-06-13 20:30:55 +02:00
|
|
|
this.distDir = join(this.dir, this.nextConfig.distDir)
|
2019-05-03 18:57:47 +02:00
|
|
|
// this.pagesDir = join(this.dir, 'pages')
|
|
|
|
this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
|
2019-05-27 20:20:33 +02:00
|
|
|
this.buildManifest = join(this.distDir, BUILD_MANIFEST)
|
2018-02-05 13:39:32 +01:00
|
|
|
|
2018-03-13 14:18:59 +01:00
|
|
|
// Only serverRuntimeConfig needs the default
|
|
|
|
// publicRuntimeConfig gets it's default in client/index.js
|
2019-03-01 20:51:13 +01:00
|
|
|
const {
|
|
|
|
serverRuntimeConfig = {},
|
|
|
|
publicRuntimeConfig,
|
|
|
|
assetPrefix,
|
|
|
|
generateEtags,
|
|
|
|
} = this.nextConfig
|
2019-01-29 13:42:07 +01:00
|
|
|
|
2018-09-28 14:05:23 +02:00
|
|
|
this.buildId = this.readBuildId()
|
2019-05-29 02:32:18 +02:00
|
|
|
|
2017-03-07 19:43:56 +01:00
|
|
|
this.renderOpts = {
|
2019-04-02 16:09:34 +02:00
|
|
|
ampBindInitData: this.nextConfig.experimental.ampBindInitData,
|
2019-04-15 09:48:14 +02:00
|
|
|
poweredByHeader: this.nextConfig.poweredByHeader,
|
2019-05-29 02:32:18 +02:00
|
|
|
canonicalBase: this.nextConfig.amp.canonicalBase,
|
2019-05-22 23:16:03 +02:00
|
|
|
autoExport: this.nextConfig.experimental.autoExport,
|
2017-03-07 19:43:56 +01:00
|
|
|
staticMarkup,
|
2017-04-18 06:18:43 +02:00
|
|
|
buildId: this.buildId,
|
2018-12-31 14:44:27 +01:00
|
|
|
generateEtags,
|
2017-03-07 19:43:56 +01:00
|
|
|
}
|
2016-12-16 21:33:08 +01:00
|
|
|
|
2018-02-27 17:50:14 +01:00
|
|
|
// Only the `publicRuntimeConfig` key is exposed to the client side
|
|
|
|
// It'll be rendered as part of __NEXT_DATA__ on the client side
|
|
|
|
if (publicRuntimeConfig) {
|
|
|
|
this.renderOpts.runtimeConfig = publicRuntimeConfig
|
2018-02-26 12:03:27 +01:00
|
|
|
}
|
|
|
|
|
2018-02-27 17:50:14 +01:00
|
|
|
// Initialize next/config with the environment configuration
|
|
|
|
envConfig.setConfig({
|
|
|
|
serverRuntimeConfig,
|
2018-12-31 14:44:27 +01:00
|
|
|
publicRuntimeConfig,
|
2018-02-27 17:50:14 +01:00
|
|
|
})
|
|
|
|
|
2018-10-01 16:31:47 +02:00
|
|
|
const routes = this.generateRoutes()
|
|
|
|
this.router = new Router(routes)
|
2019-05-03 18:57:47 +02:00
|
|
|
|
2018-02-27 17:50:14 +01:00
|
|
|
this.setAssetPrefix(assetPrefix)
|
2016-12-16 21:33:08 +01:00
|
|
|
}
|
2016-10-06 01:52:50 +02:00
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
private currentPhase(): string {
|
2019-01-26 02:01:16 +01:00
|
|
|
return PHASE_PRODUCTION_SERVER
|
2017-07-15 12:29:10 +02:00
|
|
|
}
|
|
|
|
|
2018-12-18 17:12:49 +01:00
|
|
|
private logError(...args: any): void {
|
2018-12-31 14:44:27 +01:00
|
|
|
if (this.quiet) return
|
|
|
|
// tslint:disable-next-line
|
2018-12-18 17:12:49 +01:00
|
|
|
console.error(...args)
|
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
private handleRequest(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl?: UrlWithParsedQuery
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<void> {
|
2017-04-07 19:58:35 +02:00
|
|
|
// Parse url if parsedUrl not provided
|
2017-07-02 07:52:39 +02:00
|
|
|
if (!parsedUrl || typeof parsedUrl !== 'object') {
|
2018-12-09 22:46:45 +01:00
|
|
|
const url: any = req.url
|
|
|
|
parsedUrl = parseUrl(url, true)
|
2017-04-07 19:58:35 +02:00
|
|
|
}
|
2017-02-09 04:22:48 +01:00
|
|
|
|
2017-04-07 19:58:35 +02:00
|
|
|
// Parse the querystring ourselves if the user doesn't handle querystring parsing
|
|
|
|
if (typeof parsedUrl.query === 'string') {
|
|
|
|
parsedUrl.query = parseQs(parsedUrl.query)
|
2016-12-16 21:33:08 +01:00
|
|
|
}
|
2017-04-07 19:58:35 +02:00
|
|
|
|
2017-06-19 09:27:35 +02:00
|
|
|
res.statusCode = 200
|
2019-05-29 13:57:26 +02:00
|
|
|
return this.run(req, res, parsedUrl).catch(err => {
|
2019-03-01 20:51:13 +01:00
|
|
|
this.logError(err)
|
|
|
|
res.statusCode = 500
|
|
|
|
res.end('Internal Server Error')
|
|
|
|
})
|
2017-04-07 19:58:35 +02:00
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
public getRequestHandler() {
|
2017-04-07 19:58:35 +02:00
|
|
|
return this.handleRequest.bind(this)
|
2016-10-06 01:52:50 +02:00
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
public setAssetPrefix(prefix?: string) {
|
2018-02-03 17:12:01 +01:00
|
|
|
this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
|
2018-02-02 15:43:36 +01:00
|
|
|
}
|
|
|
|
|
2018-10-01 16:31:47 +02:00
|
|
|
// Backwards compatibility
|
2018-12-31 14:44:27 +01:00
|
|
|
public async prepare(): Promise<void> {}
|
2016-10-17 09:07:41 +02:00
|
|
|
|
2018-09-28 14:05:23 +02:00
|
|
|
// Backwards compatibility
|
2018-12-31 14:44:27 +01:00
|
|
|
private async close(): Promise<void> {}
|
2018-09-28 14:05:23 +02:00
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
private setImmutableAssetCacheControl(res: ServerResponse) {
|
2018-09-28 14:05:23 +02:00
|
|
|
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
|
2016-12-17 05:04:40 +01:00
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
private generateRoutes(): Route[] {
|
2018-12-09 22:46:45 +01:00
|
|
|
const routes: Route[] = [
|
2018-09-28 14:05:23 +02:00
|
|
|
{
|
2018-10-01 16:31:47 +02:00
|
|
|
match: route('/_next/static/:path*'),
|
2018-12-09 22:46:45 +01:00
|
|
|
fn: async (req, res, params, parsedUrl) => {
|
2018-09-28 14:05:23 +02:00
|
|
|
// The commons folder holds commonschunk files
|
|
|
|
// The chunks folder holds dynamic entries
|
|
|
|
// The buildId folder holds pages and potentially other assets. As buildId changes per build it can be long-term cached.
|
2019-03-01 20:51:13 +01:00
|
|
|
if (
|
|
|
|
params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
|
|
|
|
params.path[0] === 'chunks' ||
|
|
|
|
params.path[0] === this.buildId
|
|
|
|
) {
|
2018-09-28 14:05:23 +02:00
|
|
|
this.setImmutableAssetCacheControl(res)
|
2018-05-19 21:43:18 +02:00
|
|
|
}
|
2019-03-01 20:51:13 +01:00
|
|
|
const p = join(
|
|
|
|
this.distDir,
|
|
|
|
CLIENT_STATIC_FILES_PATH,
|
2019-05-29 13:57:26 +02:00
|
|
|
...(params.path || [])
|
2019-03-01 20:51:13 +01:00
|
|
|
)
|
2018-12-09 22:46:45 +01:00
|
|
|
await this.serveStatic(req, res, p, parsedUrl)
|
2018-12-31 14:44:27 +01:00
|
|
|
},
|
2017-04-03 20:10:24 +02:00
|
|
|
},
|
2018-09-28 14:05:23 +02:00
|
|
|
{
|
2018-10-01 16:31:47 +02:00
|
|
|
match: route('/_next/:path*'),
|
2018-09-28 14:05:23 +02:00
|
|
|
// This path is needed because `render()` does a check for `/_next` and the calls the routing again
|
2018-12-09 22:46:45 +01:00
|
|
|
fn: async (req, res, _params, parsedUrl) => {
|
2018-09-28 14:05:23 +02:00
|
|
|
await this.render404(req, res, parsedUrl)
|
2018-12-31 14:44:27 +01:00
|
|
|
},
|
2018-09-28 14:05:23 +02:00
|
|
|
},
|
|
|
|
{
|
2018-11-14 09:55:25 +01:00
|
|
|
// It's very important to keep this route's param optional.
|
|
|
|
// (but it should support as many params as needed, separated by '/')
|
|
|
|
// Otherwise this will lead to a pretty simple DOS attack.
|
2018-09-28 14:05:23 +02:00
|
|
|
// See more: https://github.com/zeit/next.js/issues/2617
|
2018-10-01 16:31:47 +02:00
|
|
|
match: route('/static/:path*'),
|
2018-12-09 22:46:45 +01:00
|
|
|
fn: async (req, res, params, parsedUrl) => {
|
2018-09-28 14:05:23 +02:00
|
|
|
const p = join(this.dir, 'static', ...(params.path || []))
|
2018-12-09 22:46:45 +01:00
|
|
|
await this.serveStatic(req, res, p, parsedUrl)
|
2018-12-31 14:44:27 +01:00
|
|
|
},
|
|
|
|
},
|
2019-05-11 13:18:56 +02:00
|
|
|
{
|
|
|
|
match: route('/api/:path*'),
|
|
|
|
fn: async (req, res, params, parsedUrl) => {
|
|
|
|
const { pathname } = parsedUrl
|
2019-06-05 13:22:09 +02:00
|
|
|
await this.handleApiRequest(
|
|
|
|
req as NextApiRequest,
|
|
|
|
res as NextApiResponse,
|
|
|
|
pathname!
|
|
|
|
)
|
2019-05-11 13:18:56 +02:00
|
|
|
},
|
|
|
|
},
|
2018-09-28 14:05:23 +02:00
|
|
|
]
|
2018-09-07 14:38:01 +02:00
|
|
|
|
2019-05-03 18:57:47 +02:00
|
|
|
if (fs.existsSync(this.publicDir)) {
|
|
|
|
routes.push(...this.generatePublicRoutes())
|
|
|
|
}
|
|
|
|
|
2018-09-09 22:32:23 +02:00
|
|
|
if (this.nextConfig.useFileSystemPublicRoutes) {
|
2019-05-27 20:20:33 +02:00
|
|
|
this.dynamicRoutes = this.nextConfig.experimental.dynamicRouting
|
|
|
|
? this.getDynamicRoutes()
|
|
|
|
: []
|
|
|
|
|
2018-11-14 09:55:25 +01:00
|
|
|
// It's very important to keep this route's param optional.
|
|
|
|
// (but it should support as many params as needed, separated by '/')
|
|
|
|
// Otherwise this will lead to a pretty simple DOS attack.
|
2018-07-24 11:24:40 +02:00
|
|
|
// See more: https://github.com/zeit/next.js/issues/2617
|
2018-09-28 14:05:23 +02:00
|
|
|
routes.push({
|
2018-10-01 16:31:47 +02:00
|
|
|
match: route('/:path*'),
|
2018-12-09 22:46:45 +01:00
|
|
|
fn: async (req, res, _params, parsedUrl) => {
|
2018-09-28 14:05:23 +02:00
|
|
|
const { pathname, query } = parsedUrl
|
2018-12-31 14:44:27 +01:00
|
|
|
if (!pathname) {
|
2018-12-09 22:46:45 +01:00
|
|
|
throw new Error('pathname is undefined')
|
|
|
|
}
|
2019-02-18 15:44:21 +01:00
|
|
|
|
2019-03-01 21:35:43 +01:00
|
|
|
await this.render(req, res, pathname, query, parsedUrl)
|
2018-12-31 14:44:27 +01:00
|
|
|
},
|
2018-09-28 14:05:23 +02:00
|
|
|
})
|
2017-01-12 16:38:43 +01:00
|
|
|
}
|
2016-10-06 01:52:50 +02:00
|
|
|
|
2018-09-28 14:05:23 +02:00
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
2019-05-11 13:18:56 +02:00
|
|
|
/**
|
|
|
|
* Resolves `API` request, in development builds on demand
|
|
|
|
* @param req http request
|
|
|
|
* @param res http response
|
|
|
|
* @param pathname path of request
|
|
|
|
*/
|
2019-05-26 23:22:43 +02:00
|
|
|
private async handleApiRequest(
|
2019-06-05 13:22:09 +02:00
|
|
|
req: NextApiRequest,
|
|
|
|
res: NextApiResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
pathname: string
|
2019-05-26 23:22:43 +02:00
|
|
|
) {
|
2019-05-11 13:18:56 +02:00
|
|
|
const resolverFunction = await this.resolveApiRequest(pathname)
|
|
|
|
if (resolverFunction === null) {
|
|
|
|
res.statusCode = 404
|
|
|
|
res.end('Not Found')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-05 13:22:09 +02:00
|
|
|
try {
|
|
|
|
// Parsing of cookies
|
|
|
|
req.cookies = parseCookies(req.headers.cookie || '')
|
|
|
|
// Parsing query string
|
|
|
|
req.query = parseQuery(req)
|
|
|
|
// // Parsing of body
|
|
|
|
req.body = await parseBody(req)
|
|
|
|
|
|
|
|
res.status = statusCode => sendStatusCode(res, statusCode)
|
|
|
|
res.send = data => sendData(res, data)
|
|
|
|
res.json = data => sendJson(res, data)
|
|
|
|
|
|
|
|
const resolver = interopDefault(require(resolverFunction))
|
|
|
|
resolver(req, res)
|
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof ApiError) {
|
|
|
|
sendError(res, e.statusCode, e.message)
|
|
|
|
} else {
|
|
|
|
sendError(res, 500, e.message)
|
|
|
|
}
|
|
|
|
}
|
2019-05-11 13:18:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolves path to resolver function
|
|
|
|
* @param pathname path of request
|
|
|
|
*/
|
|
|
|
private resolveApiRequest(pathname: string) {
|
2019-05-26 23:22:43 +02:00
|
|
|
return getPagePath(
|
|
|
|
pathname,
|
|
|
|
this.distDir,
|
2019-05-29 13:57:26 +02:00
|
|
|
this.nextConfig.target === 'serverless'
|
2019-05-26 23:22:43 +02:00
|
|
|
)
|
2019-05-11 13:18:56 +02:00
|
|
|
}
|
|
|
|
|
2019-05-03 18:57:47 +02:00
|
|
|
private generatePublicRoutes(): Route[] {
|
|
|
|
const routes: Route[] = []
|
|
|
|
const publicFiles = recursiveReadDirSync(this.publicDir)
|
2019-06-10 02:18:38 +02:00
|
|
|
const serverBuildPath = join(
|
|
|
|
this.distDir,
|
|
|
|
this.nextConfig.target === 'serverless'
|
|
|
|
? SERVERLESS_DIRECTORY
|
|
|
|
: SERVER_DIRECTORY
|
|
|
|
)
|
2019-05-03 18:57:47 +02:00
|
|
|
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
publicFiles.forEach(path => {
|
2019-05-03 18:57:47 +02:00
|
|
|
const unixPath = path.replace(/\\/g, '/')
|
|
|
|
// Only include public files that will not replace a page path
|
|
|
|
if (!pagesManifest[unixPath]) {
|
|
|
|
routes.push({
|
|
|
|
match: route(unixPath),
|
|
|
|
fn: async (req, res, _params, parsedUrl) => {
|
|
|
|
const p = join(this.publicDir, unixPath)
|
|
|
|
await this.serveStatic(req, res, p, parsedUrl)
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
2019-05-27 20:20:33 +02:00
|
|
|
private getDynamicRoutes() {
|
|
|
|
const manifest = require(this.buildManifest)
|
2019-05-29 13:57:26 +02:00
|
|
|
const dynamicRoutedPages = Object.keys(manifest.pages).filter(p =>
|
|
|
|
p.includes('/$')
|
2019-05-27 20:20:33 +02:00
|
|
|
)
|
2019-05-30 22:42:45 +02:00
|
|
|
return getSortedRoutes(dynamicRoutedPages).map(page => ({
|
|
|
|
page,
|
|
|
|
match: getRouteMatcher(getRouteRegex(page)),
|
|
|
|
}))
|
2019-05-27 20:20:33 +02:00
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
private async run(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl: UrlWithParsedQuery
|
2019-03-01 20:51:13 +01:00
|
|
|
) {
|
2018-11-04 01:22:33 +01:00
|
|
|
try {
|
|
|
|
const fn = this.router.match(req, res, parsedUrl)
|
|
|
|
if (fn) {
|
|
|
|
await fn()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'DECODE_FAILED') {
|
|
|
|
res.statusCode = 400
|
|
|
|
return this.renderError(null, req, res, '/_error', {})
|
|
|
|
}
|
|
|
|
throw err
|
2017-01-12 16:38:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'GET' || req.method === 'HEAD') {
|
2017-02-02 07:51:08 +01:00
|
|
|
await this.render404(req, res, parsedUrl)
|
2017-01-12 16:38:43 +01:00
|
|
|
} else {
|
|
|
|
res.statusCode = 501
|
2018-09-27 21:10:53 +02:00
|
|
|
res.end('Not Implemented')
|
2016-10-06 01:52:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
private async sendHTML(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
html: string
|
2019-03-01 20:51:13 +01:00
|
|
|
) {
|
2019-04-15 09:48:14 +02:00
|
|
|
const { generateEtags, poweredByHeader } = this.renderOpts
|
|
|
|
return sendHTML(req, res, html, { generateEtags, poweredByHeader })
|
2018-12-09 22:46:45 +01:00
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public async render(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
pathname: string,
|
|
|
|
query: ParsedUrlQuery = {},
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl?: UrlWithParsedQuery
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<void> {
|
2018-12-09 22:46:45 +01:00
|
|
|
const url: any = req.url
|
|
|
|
if (isInternalUrl(url)) {
|
2017-04-07 19:58:35 +02:00
|
|
|
return this.handleRequest(req, res, parsedUrl)
|
|
|
|
}
|
|
|
|
|
2018-11-18 20:44:50 +01:00
|
|
|
if (isBlockedPage(pathname)) {
|
2018-12-09 22:46:45 +01:00
|
|
|
return this.render404(req, res, parsedUrl)
|
2017-07-06 14:29:25 +02:00
|
|
|
}
|
|
|
|
|
2019-03-01 21:35:43 +01:00
|
|
|
const html = await this.renderToHTML(req, res, pathname, query, {
|
2019-05-26 23:22:43 +02:00
|
|
|
dataOnly:
|
|
|
|
(this.renderOpts.ampBindInitData && Boolean(query.dataOnly)) ||
|
|
|
|
(req.headers &&
|
|
|
|
(req.headers.accept || '').indexOf('application/amp.bind+json') !==
|
|
|
|
-1),
|
2019-03-01 21:35:43 +01:00
|
|
|
})
|
2018-12-09 22:46:45 +01:00
|
|
|
// Request was ended by the user
|
|
|
|
if (html === null) {
|
2018-02-01 23:25:30 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-12-09 22:46:45 +01:00
|
|
|
return this.sendHTML(req, res, html)
|
2016-12-16 21:33:08 +01:00
|
|
|
}
|
2016-10-19 14:41:45 +02:00
|
|
|
|
2019-05-26 23:22:43 +02:00
|
|
|
private async findPageComponents(
|
2019-03-01 20:51:13 +01:00
|
|
|
pathname: string,
|
2019-05-29 13:57:26 +02:00
|
|
|
query: ParsedUrlQuery = {}
|
2019-03-01 20:51:13 +01:00
|
|
|
) {
|
2019-05-26 23:22:43 +02:00
|
|
|
const serverless =
|
|
|
|
!this.renderOpts.dev && this.nextConfig.target === 'serverless'
|
2019-05-22 18:36:53 +02:00
|
|
|
// try serving a static AMP version first
|
|
|
|
if (query.amp) {
|
|
|
|
try {
|
2019-05-26 23:22:43 +02:00
|
|
|
return await loadComponents(
|
|
|
|
this.distDir,
|
|
|
|
this.buildId,
|
|
|
|
(pathname === '/' ? '/index' : pathname) + '.amp',
|
2019-05-29 13:57:26 +02:00
|
|
|
serverless
|
2019-05-26 23:22:43 +02:00
|
|
|
)
|
2019-05-22 18:36:53 +02:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code !== 'ENOENT') throw err
|
|
|
|
}
|
|
|
|
}
|
2019-05-26 23:22:43 +02:00
|
|
|
return await loadComponents(
|
|
|
|
this.distDir,
|
|
|
|
this.buildId,
|
|
|
|
pathname,
|
2019-05-29 13:57:26 +02:00
|
|
|
serverless
|
2019-05-26 23:22:43 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
private async renderToHTMLWithComponents(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
pathname: string,
|
|
|
|
query: ParsedUrlQuery = {},
|
|
|
|
result: LoadComponentsReturnType,
|
2019-05-29 13:57:26 +02:00
|
|
|
opts: any
|
2019-05-26 23:22:43 +02:00
|
|
|
) {
|
2019-05-22 18:36:53 +02:00
|
|
|
// handle static page
|
2019-05-26 23:22:43 +02:00
|
|
|
if (typeof result.Component === 'string') {
|
|
|
|
return result.Component
|
|
|
|
}
|
|
|
|
|
2019-05-22 18:36:53 +02:00
|
|
|
// handle serverless
|
2019-05-26 23:22:43 +02:00
|
|
|
if (
|
|
|
|
typeof result.Component === 'object' &&
|
2019-05-22 18:36:53 +02:00
|
|
|
typeof result.Component.renderReqToHTML === 'function'
|
|
|
|
) {
|
|
|
|
return result.Component.renderReqToHTML(req, res)
|
|
|
|
}
|
2019-05-26 23:22:43 +02:00
|
|
|
|
2019-06-10 02:16:14 +02:00
|
|
|
return renderToHTML(req, res, pathname, query, {
|
|
|
|
...result,
|
|
|
|
...opts,
|
|
|
|
PageConfig: result.PageConfig,
|
|
|
|
})
|
2018-12-18 17:12:49 +01:00
|
|
|
}
|
|
|
|
|
2019-05-27 20:20:33 +02:00
|
|
|
public renderToHTML(
|
2019-03-01 20:51:13 +01:00
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
pathname: string,
|
|
|
|
query: ParsedUrlQuery = {},
|
2019-05-26 23:22:43 +02:00
|
|
|
{
|
|
|
|
amphtml,
|
|
|
|
dataOnly,
|
|
|
|
hasAmp,
|
|
|
|
}: {
|
|
|
|
amphtml?: boolean
|
|
|
|
hasAmp?: boolean
|
2019-05-29 13:57:26 +02:00
|
|
|
dataOnly?: boolean
|
|
|
|
} = {}
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<string | null> {
|
2019-05-27 20:20:33 +02:00
|
|
|
return this.findPageComponents(pathname, query)
|
|
|
|
.then(
|
2019-05-29 13:57:26 +02:00
|
|
|
result => {
|
2019-05-27 20:20:33 +02:00
|
|
|
return this.renderToHTMLWithComponents(
|
|
|
|
req,
|
|
|
|
res,
|
|
|
|
pathname,
|
|
|
|
query,
|
|
|
|
result,
|
2019-05-29 13:57:26 +02:00
|
|
|
{ ...this.renderOpts, amphtml, hasAmp, dataOnly }
|
2019-05-27 20:20:33 +02:00
|
|
|
)
|
|
|
|
},
|
2019-05-29 13:57:26 +02:00
|
|
|
err => {
|
2019-05-27 20:20:33 +02:00
|
|
|
if (err.code !== 'ENOENT' || !this.dynamicRoutes) {
|
|
|
|
return Promise.reject(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const dynamicRoute of this.dynamicRoutes) {
|
|
|
|
const params = dynamicRoute.match(pathname)
|
|
|
|
if (!params) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.findPageComponents(dynamicRoute.page, query).then(
|
2019-05-29 13:57:26 +02:00
|
|
|
result =>
|
2019-05-27 20:20:33 +02:00
|
|
|
this.renderToHTMLWithComponents(
|
|
|
|
req,
|
|
|
|
res,
|
|
|
|
dynamicRoute.page,
|
|
|
|
{ ...query, ...params },
|
|
|
|
result,
|
2019-05-29 13:57:26 +02:00
|
|
|
{ ...this.renderOpts, amphtml, hasAmp, dataOnly }
|
|
|
|
)
|
2019-05-27 20:20:33 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.reject(err)
|
2019-05-29 13:57:26 +02:00
|
|
|
}
|
2019-03-01 20:51:13 +01:00
|
|
|
)
|
2019-05-29 13:57:26 +02:00
|
|
|
.catch(err => {
|
2019-05-27 20:20:33 +02:00
|
|
|
if (err && err.code === 'ENOENT') {
|
|
|
|
res.statusCode = 404
|
|
|
|
return this.renderErrorToHTML(null, req, res, pathname, query)
|
|
|
|
} else {
|
|
|
|
this.logError(err)
|
|
|
|
res.statusCode = 500
|
|
|
|
return this.renderErrorToHTML(err, req, res, pathname, query)
|
|
|
|
}
|
|
|
|
})
|
2016-11-24 15:03:16 +01:00
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public async renderError(
|
|
|
|
err: Error | null,
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
pathname: string,
|
2019-05-29 13:57:26 +02:00
|
|
|
query: ParsedUrlQuery = {}
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<void> {
|
|
|
|
res.setHeader(
|
|
|
|
'Cache-Control',
|
2019-05-29 13:57:26 +02:00
|
|
|
'no-cache, no-store, max-age=0, must-revalidate'
|
2019-03-01 20:51:13 +01:00
|
|
|
)
|
2016-12-16 21:33:08 +01:00
|
|
|
const html = await this.renderErrorToHTML(err, req, res, pathname, query)
|
2018-12-31 14:44:27 +01:00
|
|
|
if (html === null) {
|
2018-12-13 01:00:46 +01:00
|
|
|
return
|
|
|
|
}
|
2018-12-09 22:46:45 +01:00
|
|
|
return this.sendHTML(req, res, html)
|
2016-10-06 01:52:50 +02:00
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public async renderErrorToHTML(
|
|
|
|
err: Error | null,
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
_pathname: string,
|
2019-05-29 13:57:26 +02:00
|
|
|
query: ParsedUrlQuery = {}
|
2019-03-01 20:51:13 +01:00
|
|
|
) {
|
2019-05-26 23:22:43 +02:00
|
|
|
const result = await this.findPageComponents('/_error', query)
|
|
|
|
return this.renderToHTMLWithComponents(req, res, '/_error', query, result, {
|
2019-03-01 20:51:13 +01:00
|
|
|
...this.renderOpts,
|
|
|
|
err,
|
|
|
|
})
|
2016-11-24 15:03:16 +01:00
|
|
|
}
|
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public async render404(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl?: UrlWithParsedQuery
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<void> {
|
2018-12-09 22:46:45 +01:00
|
|
|
const url: any = req.url
|
|
|
|
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
|
2018-12-31 14:44:27 +01:00
|
|
|
if (!pathname) {
|
2018-12-09 22:46:45 +01:00
|
|
|
throw new Error('pathname is undefined')
|
|
|
|
}
|
2016-12-16 21:33:08 +01:00
|
|
|
res.statusCode = 404
|
2017-02-16 03:48:35 +01:00
|
|
|
return this.renderError(null, req, res, pathname, query)
|
2016-12-16 21:33:08 +01:00
|
|
|
}
|
2016-11-03 16:12:37 +01:00
|
|
|
|
2019-03-01 20:51:13 +01:00
|
|
|
public async serveStatic(
|
|
|
|
req: IncomingMessage,
|
|
|
|
res: ServerResponse,
|
|
|
|
path: string,
|
2019-05-29 13:57:26 +02:00
|
|
|
parsedUrl?: UrlWithParsedQuery
|
2019-03-01 20:51:13 +01:00
|
|
|
): Promise<void> {
|
2017-06-01 02:16:32 +02:00
|
|
|
if (!this.isServeableUrl(path)) {
|
2018-12-09 22:46:45 +01:00
|
|
|
return this.render404(req, res, parsedUrl)
|
2017-06-01 02:16:32 +02:00
|
|
|
}
|
|
|
|
|
2017-01-01 20:36:37 +01:00
|
|
|
try {
|
2018-12-09 22:46:45 +01:00
|
|
|
await serveStatic(req, res, path)
|
2017-01-01 20:36:37 +01:00
|
|
|
} catch (err) {
|
2018-11-30 17:09:23 +01:00
|
|
|
if (err.code === 'ENOENT' || err.statusCode === 404) {
|
2018-12-09 22:46:45 +01:00
|
|
|
this.render404(req, res, parsedUrl)
|
2017-01-01 20:36:37 +01:00
|
|
|
} else {
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
private isServeableUrl(path: string): boolean {
|
2017-06-01 02:16:32 +02:00
|
|
|
const resolved = resolve(path)
|
|
|
|
if (
|
2018-06-04 15:45:39 +02:00
|
|
|
resolved.indexOf(join(this.distDir) + sep) !== 0 &&
|
2019-05-03 18:57:47 +02:00
|
|
|
resolved.indexOf(join(this.dir, 'static') + sep) !== 0 &&
|
|
|
|
resolved.indexOf(join(this.dir, 'public') + sep) !== 0
|
2017-06-01 02:16:32 +02:00
|
|
|
) {
|
|
|
|
// Seems like the user is trying to traverse the filesystem.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2018-12-31 14:44:27 +01:00
|
|
|
private readBuildId(): string {
|
2018-12-06 16:46:53 +01:00
|
|
|
const buildIdFile = join(this.distDir, BUILD_ID_FILE)
|
|
|
|
try {
|
|
|
|
return fs.readFileSync(buildIdFile, 'utf8').trim()
|
|
|
|
} catch (err) {
|
|
|
|
if (!fs.existsSync(buildIdFile)) {
|
2019-03-01 20:51:13 +01:00
|
|
|
throw new Error(
|
|
|
|
`Could not find a valid build in the '${
|
|
|
|
this.distDir
|
2019-05-29 13:57:26 +02:00
|
|
|
}' directory! Try building your app with 'next build' before starting the server.`
|
2019-03-01 20:51:13 +01:00
|
|
|
)
|
2018-12-06 16:46:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
throw err
|
2018-07-25 13:45:42 +02:00
|
|
|
}
|
2017-01-11 21:16:18 +01:00
|
|
|
}
|
2017-02-21 00:48:17 +01:00
|
|
|
}
|