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/render.tsx
Tim Neutkens 0f23faf81f
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 11:39:12 +01:00

213 lines
6.5 KiB
TypeScript

import {IncomingMessage, ServerResponse} from 'http'
import { ParsedUrlQuery } from 'querystring'
import React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import Router from '../lib/router/router'
import { loadGetInitialProps, isResSent } from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
import Loadable from '../lib/loadable'
import LoadableCapture from '../lib/loadable-capture'
import {getDynamicImportBundles, Manifest as ReactLoadableManifest, ManifestItem} from './get-dynamic-import-bundles'
import {getPageFiles, BuildManifest} from './get-page-files'
type Enhancer = (Component: React.ComponentType) => React.ComponentType
type ComponentsEnhancer = {enhanceApp?: Enhancer, enhanceComponent?: Enhancer}|Enhancer
function enhanceComponents(options: ComponentsEnhancer, App: React.ComponentType, Component: React.ComponentType): {
App: React.ComponentType,
Component: React.ComponentType
} {
// For backwards compatibility
if(typeof options === 'function') {
return {
App: App,
Component: options(Component)
}
}
return {
App: options.enhanceApp ? options.enhanceApp(App) : App,
Component: options.enhanceComponent ? options.enhanceComponent(Component) : Component
}
}
function render(renderElementToString: (element: React.ReactElement<any>) => string, element: React.ReactElement<any>): {html: string, head: any} {
let html
let head
try {
html = renderElementToString(element)
} finally {
head = Head.rewind() || defaultHead()
}
return { html, head }
}
type RenderOpts = {
staticMarkup: boolean,
buildId: string,
runtimeConfig?: {[key: string]: any},
assetPrefix?: string,
err?: Error|null,
nextExport?: boolean,
dev?: boolean,
buildManifest: BuildManifest,
reactLoadableManifest: ReactLoadableManifest,
Component: React.ComponentType,
Document: React.ComponentType,
App: React.ComponentType,
ErrorDebug?: React.ComponentType<{error: Error}>
}
function renderDocument(Document: React.ComponentType, {
props,
docProps,
pathname,
query,
buildId,
assetPrefix,
runtimeConfig,
nextExport,
dynamicImportsIds,
err,
dev,
staticMarkup,
devFiles,
files,
dynamicImports,
}: RenderOpts & {
props: any,
docProps: any,
pathname: string,
query: ParsedUrlQuery,
dynamicImportsIds: string[],
dynamicImports: ManifestItem[],
files: string[]
devFiles: string[],
}): string {
return '<!DOCTYPE html>' + renderToStaticMarkup(
<Document
__NEXT_DATA__={{
props, // The result of getInitialProps
page: pathname, // The rendered page
query, // querystring parsed / passed by the user
buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
nextExport, // If this is a page exported by `next export`
dynamicIds: dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: (err) ? serializeError(dev, err) : undefined // Error if one happened, otherwise don't sent in the resulting HTML
}}
staticMarkup={staticMarkup}
devFiles={devFiles}
files={files}
dynamicImports={dynamicImports}
assetPrefix={assetPrefix}
{...docProps}
/>
)
}
export async function renderToHTML (req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery, renderOpts: RenderOpts): Promise<string|null> {
const {
err,
dev = false,
staticMarkup = false,
App,
Document,
Component,
buildManifest,
reactLoadableManifest,
ErrorDebug
} = renderOpts
await Loadable.preloadAll() // Make sure all dynamic imports are loaded
if (dev) {
const { isValidElementType } = require('react-is')
if (!isValidElementType(Component)) {
throw new Error(`The default export is not a React Component in page: "${pathname}"`)
}
if (!isValidElementType(App)) {
throw new Error(`The default export is not a React Component in page: "/_app"`)
}
if (!isValidElementType(Document)) {
throw new Error(`The default export is not a React Component in page: "/_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})
// the response might be finished on the getInitialProps call
if (isResSent(res)) return null
const devFiles = buildManifest.devFiles
const files = [
...new Set([
...getPageFiles(buildManifest, pathname),
...getPageFiles(buildManifest, '/_app'),
...getPageFiles(buildManifest, '/_error')
])
]
const reactLoadableModules: string[] = []
const renderPage = (options: ComponentsEnhancer = {}): {html: string, head: any} => {
const renderElementToString = staticMarkup ? renderToStaticMarkup : renderToString
if(err && ErrorDebug) {
return render(renderElementToString, <ErrorDebug error={err} />)
}
const {App: EnhancedApp, Component: EnhancedComponent} = enhanceComponents(options, App, Component)
return render(renderElementToString,
<LoadableCapture report={(moduleName) => reactLoadableModules.push(moduleName)}>
<EnhancedApp
Component={EnhancedComponent}
router={router}
{...props}
/>
</LoadableCapture>
)
}
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
// the response might be finshed on the getInitialProps call
if (isResSent(res)) return null
const dynamicImports = [...getDynamicImportBundles(reactLoadableManifest, reactLoadableModules)]
const dynamicImportsIds: any = dynamicImports.map((bundle) => bundle.id)
return renderDocument(Document, {
...renderOpts,
props,
docProps,
pathname,
query,
dynamicImportsIds,
dynamicImports,
files,
devFiles
})
}
function errorToJSON (err: Error): Error {
const { name, message, stack } = err
return { name, message, stack }
}
function serializeError (dev: boolean|undefined, err: Error): Error & {statusCode?: number} {
if (dev) {
return errorToJSON(err)
}
return { name: 'Internal Server Error.', message: '500 - Internal Server Error.', statusCode: 500 }
}