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

317 lines
10 KiB
TypeScript
Raw Normal View History

/* eslint-disable import/first */
import {IncomingMessage, ServerResponse} from 'http'
2017-06-01 00:16:32 +00:00
import { resolve, join, sep } from 'path'
import { parse as parseUrl, UrlWithParsedQuery } from 'url'
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import fs from 'fs'
import {renderToHTML} from './render'
import {sendHTML} from './send-html'
import {serveStatic} from './serve-static'
import Router, {route, Route} from './router'
import { isInternalUrl, isBlockedPage } from './utils'
2018-10-01 22:55:31 +00:00
import loadConfig from 'next-server/next-config'
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 10:39:12 +00:00
import {PHASE_PRODUCTION_SERVER, BUILD_ID_FILE, CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_RUNTIME} from 'next-server/constants'
import * as envConfig from '../lib/runtime-config'
import {loadComponents} from './load-components'
type NextConfig = any
type ServerConstructor = {
dir?: string,
staticMarkup?: boolean,
quiet?: boolean,
conf?: NextConfig,
}
2016-10-05 23:52:50 +00:00
export default class Server {
dir: string
quiet: boolean
nextConfig: NextConfig
distDir: string
buildId: string
renderOpts: {
staticMarkup: boolean,
buildId: string,
generateEtags: boolean,
runtimeConfig?: {[key: string]: any},
assetPrefix?: string,
}
router: Router
public constructor({ dir = '.', staticMarkup = false, quiet = false, conf = null }: ServerConstructor = {}) {
2016-10-06 11:05:52 +00:00
this.dir = resolve(dir)
this.quiet = quiet
const phase = this.currentPhase()
this.nextConfig = loadConfig(phase, this.dir, conf)
2018-06-13 18:30:55 +00:00
this.distDir = join(this.dir, this.nextConfig.distDir)
// Only serverRuntimeConfig needs the default
// publicRuntimeConfig gets it's default in client/index.js
const {serverRuntimeConfig = {}, publicRuntimeConfig, assetPrefix, generateEtags} = this.nextConfig
this.buildId = this.readBuildId()
this.renderOpts = {
staticMarkup,
buildId: this.buildId,
generateEtags,
}
2018-02-27 16:50:14 +00: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-27 16:50:14 +00:00
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig,
2018-02-27 16:50:14 +00:00
})
const routes = this.generateRoutes()
this.router = new Router(routes)
2018-02-27 16:50:14 +00:00
this.setAssetPrefix(assetPrefix)
}
2016-10-05 23:52:50 +00:00
private currentPhase(): string {
return PHASE_PRODUCTION_SERVER
}
private logError(...args: any): void {
if (this.quiet) return
// tslint:disable-next-line
console.error(...args)
}
private handleRequest(req: IncomingMessage, res: ServerResponse, parsedUrl?: UrlWithParsedQuery): Promise<void> {
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
const url: any = req.url
parsedUrl = parseUrl(url, true)
}
// Parse the querystring ourselves if the user doesn't handle querystring parsing
if (typeof parsedUrl.query === 'string') {
parsedUrl.query = parseQs(parsedUrl.query)
}
res.statusCode = 200
return this.run(req, res, parsedUrl)
.catch((err) => {
this.logError(err)
res.statusCode = 500
res.end('Internal Server Error')
})
}
public getRequestHandler() {
return this.handleRequest.bind(this)
2016-10-05 23:52:50 +00:00
}
public setAssetPrefix(prefix?: string) {
this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
}
// Backwards compatibility
public async prepare(): Promise<void> {}
2016-10-17 07:07:41 +00:00
// Backwards compatibility
private async close(): Promise<void> {}
private setImmutableAssetCacheControl(res: ServerResponse) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
}
private generateRoutes(): Route[] {
const routes: Route[] = [
{
match: route('/_next/static/:path*'),
fn: async (req, res, params, parsedUrl) => {
// 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.
if (params.path[0] === CLIENT_STATIC_FILES_RUNTIME || params.path[0] === 'chunks' || params.path[0] === this.buildId) {
this.setImmutableAssetCacheControl(res)
}
const p = join(this.distDir, CLIENT_STATIC_FILES_PATH, ...(params.path || []))
await this.serveStatic(req, res, p, parsedUrl)
},
},
{
match: route('/_next/:path*'),
// This path is needed because `render()` does a check for `/_next` and the calls the routing again
fn: async (req, res, _params, parsedUrl) => {
await this.render404(req, res, parsedUrl)
},
},
{
// 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.
// See more: https://github.com/zeit/next.js/issues/2617
match: route('/static/:path*'),
fn: async (req, res, params, parsedUrl) => {
const p = join(this.dir, 'static', ...(params.path || []))
await this.serveStatic(req, res, p, parsedUrl)
},
},
]
if (this.nextConfig.useFileSystemPublicRoutes) {
// 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.
// See more: https://github.com/zeit/next.js/issues/2617
routes.push({
match: route('/:path*'),
fn: async (req, res, _params, parsedUrl) => {
const { pathname, query } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
await this.render(req, res, pathname, query, parsedUrl)
},
})
}
2016-10-05 23:52:50 +00:00
return routes
}
private async run(req: IncomingMessage, res: ServerResponse, parsedUrl: UrlWithParsedQuery) {
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
}
if (req.method === 'GET' || req.method === 'HEAD') {
await this.render404(req, res, parsedUrl)
} else {
res.statusCode = 501
res.end('Not Implemented')
2016-10-05 23:52:50 +00:00
}
}
private async sendHTML(req: IncomingMessage, res: ServerResponse, html: string) {
const {generateEtags} = this.renderOpts
return sendHTML(req, res, html, {generateEtags})
}
public async render(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}, parsedUrl?: UrlWithParsedQuery): Promise<void> {
const url: any = req.url
if (isInternalUrl(url)) {
return this.handleRequest(req, res, parsedUrl)
}
if (isBlockedPage(pathname)) {
return this.render404(req, res, parsedUrl)
}
const html = await this.renderToHTML(req, res, pathname, query)
// Request was ended by the user
if (html === null) {
return
}
if (this.nextConfig.poweredByHeader) {
res.setHeader('X-Powered-By', 'Next.js ' + process.env.NEXT_VERSION)
}
return this.sendHTML(req, res, html)
}
2016-10-19 12:41:45 +00:00
private async renderToHTMLWithComponents(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}, opts: any) {
const result = await loadComponents(this.distDir, this.buildId, pathname)
return renderToHTML(req, res, pathname, query, {...result, ...opts})
}
public async renderToHTML(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}): Promise<string|null> {
try {
// To make sure the try/catch is executed
const html = await this.renderToHTMLWithComponents(req, res, pathname, query, this.renderOpts)
return html
} catch (err) {
if (err.code === 'ENOENT') {
2018-12-13 18:46:16 +00:00
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-10-05 23:52:50 +00:00
}
}
}
public async renderError(err: Error|null, req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}): Promise<void> {
res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
const html = await this.renderErrorToHTML(err, req, res, pathname, query)
if (html === null) {
return
}
return this.sendHTML(req, res, html)
2016-10-05 23:52:50 +00:00
}
public async renderErrorToHTML(err: Error|null, req: IncomingMessage, res: ServerResponse, _pathname: string, query: ParsedUrlQuery = {}) {
return this.renderToHTMLWithComponents(req, res, '/_error', query, {...this.renderOpts, err})
}
public async render404(req: IncomingMessage, res: ServerResponse, parsedUrl?: UrlWithParsedQuery): Promise<void> {
const url: any = req.url
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
if (!pathname) {
throw new Error('pathname is undefined')
}
res.statusCode = 404
return this.renderError(null, req, res, pathname, query)
}
public async serveStatic(req: IncomingMessage, res: ServerResponse, path: string, parsedUrl?: UrlWithParsedQuery): Promise<void> {
2017-06-01 00:16:32 +00:00
if (!this.isServeableUrl(path)) {
return this.render404(req, res, parsedUrl)
2017-06-01 00:16:32 +00:00
}
try {
await serveStatic(req, res, path)
} catch (err) {
2018-11-30 16:09:23 +00:00
if (err.code === 'ENOENT' || err.statusCode === 404) {
this.render404(req, res, parsedUrl)
} else {
throw err
}
}
}
private isServeableUrl(path: string): boolean {
2017-06-01 00:16:32 +00:00
const resolved = resolve(path)
if (
resolved.indexOf(join(this.distDir) + sep) !== 0 &&
2017-06-01 00:16:32 +00:00
resolved.indexOf(join(this.dir, 'static') + sep) !== 0
) {
// Seems like the user is trying to traverse the filesystem.
return false
}
return true
}
private readBuildId(): string {
const buildIdFile = join(this.distDir, BUILD_ID_FILE)
try {
return fs.readFileSync(buildIdFile, 'utf8').trim()
} catch (err) {
if (!fs.existsSync(buildIdFile)) {
throw new Error(`Could not find a valid build in the '${this.distDir}' directory! Try building your app with 'next build' before starting the server.`)
}
throw err
}
}
}