rsnext/packages/next/next-server/server/config.ts

520 lines
15 KiB
TypeScript
Raw Normal View History

2020-03-29 00:43:52 +01:00
import chalk from 'next/dist/compiled/chalk'
2020-03-29 18:21:53 +02:00
import findUp from 'next/dist/compiled/find-up'
import os from 'os'
import { basename, extname } from 'path'
import * as Log from '../../build/output/log'
import { CONFIG_FILE } from '../lib/constants'
import { execOnce } from '../lib/utils'
const targets = ['server', 'serverless', 'experimental-serverless-trace']
const reactModes = ['legacy', 'blocking', 'concurrent']
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
const defaultConfig: { [key: string]: any } = {
env: [],
webpack: null,
webpackDevMiddleware: null,
distDir: '.next',
assetPrefix: '',
configOrigin: 'default',
useFileSystemPublicRoutes: true,
generateBuildId: () => null,
generateEtags: true,
2019-04-23 11:54:08 +02:00
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
target: 'server',
poweredByHeader: true,
compress: true,
analyticsId: process.env.VERCEL_ANALYTICS_ID || '',
images: {
deviceSizes: [320, 420, 768, 1024, 1200],
iconSizes: [],
domains: [],
path: '/_next/image',
loader: 'default',
},
devIndicators: {
buildActivity: true,
autoPrerender: true,
},
onDemandEntries: {
maxInactiveAge: 60 * 1000,
pagesBufferLength: 2,
},
amp: {
canonicalBase: '',
},
basePath: '',
sassOptions: {},
trailingSlash: false,
experimental: {
cpus: Math.max(
1,
(Number(process.env.CIRCLE_NODE_TOTAL) ||
(os.cpus() || { length: 1 }).length) - 1
),
modern: false,
Initial plugins implementation (#9139) * Add initial bit for plugins * Add checks for needed metadata values * Add test * Initial plugins changes * Add handling for _app middleware * Add loading of _document middleware and handling of multiple default export syntaxes * Fix insert order for middleware member expression * Remove early return from middleware plugin from testing * Add tests for current plugin middlewares * Update test plugin package.json * Update handling for class default export * Update to use webpack loader instead of babel plugin, remove redundant middleware naming, and add field for required env for plugins * Add middleware to support material-ui use case and example material-ui plugin * Update tests and remove tests stuff from google analytics plugin * Remove old plugin suite * Add init-server middleware * Exit hard without stack trace when error in collecting plugins * Add on-error-client and on-error-server and update to run init-server with next-start in serverless mode * Update init-client for google analytics plugin * Add example Sentry plugin and update with-sentry-simple * Remove middleware field/folder and use src dir for plugins * Add post-hydration middleware and update material-ui plugin * Put plugins code behind flag * Update chromedriver * Revert "Update chromedriver" This reverts commit 1461e978e677f7da05e29e0415ec614a04bf65f9. * Update lock file * Remove un-needed _app for sentry example * Add auto loading of scoped packages, add plugins config for manually listing plugins, and update to only collect plugins once * Update example plugins * Expose plugins' config * Rename plugin lifecycles and add babel-preset-build * Rename other methods with unstable * Update log when plugin config overrides auto-detecting
2019-11-01 20:13:13 +01:00
plugins: false,
2019-09-11 20:10:51 +02:00
profiling: false,
Add experimental SPR support (#8832) * initial commit for SPRv2 * Add initial SPR cache handling * update SPR handling * Implement SPR handling in render * Update tests, handle caching with serverless next start, add TODOs, and update manifest generating * Handle no prerender-manifest from not being used * Fix url.parse error * Apply suggestions from code review Co-Authored-By: Joe Haddad <joe.haddad@zeit.co> * Replace set with constants in next-page-config * simplify sprStatus.used * Add error if getStaticProps is used with getInitialProps * Remove stale TODO * Update revalidate values in SPR cache for non-seeded routes * Apply suggestions from code review * Remove concurrency type * Rename variable for clarity * Add copying prerender files during export * Add comment for clarity * Fix exporting * Update comment * Add additional note * Rename variable * Update to not re-export SPR pages from build * Hard navigate when fetching data fails * Remove default extension * Add brackets * Add checking output files to prerender tests * Adjust export move logic * Clarify behavior of export aggregation * Update variable names for clarity * Update tests * Add comment * s/an oxymoron/contradictory/ * rename * Extract error case * Add tests for exporting SPR pages and update /_next/data endpoint to end with .json * Relocate variable * Adjust route building * Rename to unstable * Rename unstable_getStaticParams * Fix linting * Only add this when a data request * Update prerender data tests * s/isServerless/isLikeServerless/ * Don't rely on query for `next start` in serverless mode * Rename var * Update renderedDuringBuild check * Add test for dynamic param with bracket * Fix serverless next start handling * remove todo * Adjust comment * Update calculateRevalidate * Remove cache logic from render.tsx * Remove extra imports * Move SPR cache logic to next-server * Remove old isDynamic prop * Add calling App getInitialProps for SPR pages * Update revalidate logic * Add isStale to SprCacheValue * Update headers for SPR * add awaiting pendingRevalidation * Dont return null for revalidation render * Adjust logic * Be sure to remove coalesced render * Fix data for serverless * Create a method coalescing utility * Remove TODO * Extract send payload helper * Wrap in-line * Move around some code * Add tests for de-duping and revalidating * Update prerender manifest test
2019-09-24 10:50:04 +02:00
sprFlushToDisk: true,
reactMode: 'legacy',
workerThreads: false,
pageEnv: false,
productionBrowserSourceMaps: false,
optimizeFonts: false,
optimizeImages: false,
scrollRestoration: false,
i18n: false,
},
future: {
excludeDefaultMomentLocales: false,
},
serverRuntimeConfig: {},
publicRuntimeConfig: {},
reactStrictMode: false,
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
}
const experimentalWarning = execOnce(() => {
Log.warn(chalk.bold('You have enabled experimental feature(s).'))
Log.warn(
`Experimental features are not covered by semver, and may cause unexpected or broken application behavior. ` +
`Use them at your own risk.`
)
console.warn()
})
function assignDefaults(userConfig: { [key: string]: any }) {
if (typeof userConfig.exportTrailingSlash !== 'undefined') {
console.warn(
chalk.yellow.bold('Warning: ') +
'The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your next.config.js.'
)
if (typeof userConfig.trailingSlash === 'undefined') {
userConfig.trailingSlash = userConfig.exportTrailingSlash
}
delete userConfig.exportTrailingSlash
}
2020-05-22 18:46:36 +02:00
const config = Object.keys(userConfig).reduce<{ [key: string]: any }>(
(currentConfig, key) => {
2020-05-22 18:46:36 +02:00
const value = userConfig[key]
2020-05-22 18:46:36 +02:00
if (value === undefined || value === null) {
return currentConfig
}
2020-05-22 18:46:36 +02:00
if (key === 'experimental' && value && value !== defaultConfig[key]) {
experimentalWarning()
}
2020-05-22 18:46:36 +02:00
if (key === 'distDir') {
if (typeof value !== 'string') {
throw new Error(
`Specified distDir is not a string, found type "${typeof value}"`
)
}
const userDistDir = value.trim()
2020-05-22 18:46:36 +02:00
// don't allow public as the distDir as this is a reserved folder for
// public files
if (userDistDir === 'public') {
throw new Error(
`The 'public' directory is reserved in Next.js and can not be set as the 'distDir'. https://err.sh/vercel/next.js/can-not-output-to-public`
2020-05-22 18:46:36 +02:00
)
}
// make sure distDir isn't an empty string as it can result in the provided
// directory being deleted in development mode
if (userDistDir.length === 0) {
throw new Error(
`Invalid distDir provided, distDir can not be an empty string. Please remove this config or set it to undefined`
)
}
}
2020-05-22 18:46:36 +02:00
if (key === 'pageExtensions') {
if (!Array.isArray(value)) {
throw new Error(
`Specified pageExtensions is not an array of strings, found "${value}". Please update this config or remove it.`
)
}
2020-05-22 18:46:36 +02:00
if (!value.length) {
throw new Error(
2020-05-22 18:46:36 +02:00
`Specified pageExtensions is an empty array. Please update it with the relevant extensions or remove it.`
)
}
2020-05-22 18:46:36 +02:00
value.forEach((ext) => {
if (typeof ext !== 'string') {
throw new Error(
`Specified pageExtensions is not an array of strings, found "${ext}" of type "${typeof ext}". Please update this config or remove it.`
)
}
})
}
2020-05-22 18:46:36 +02:00
if (!!value && value.constructor === Object) {
currentConfig[key] = {
2020-05-22 18:46:36 +02:00
...defaultConfig[key],
...Object.keys(value).reduce<any>((c, k) => {
const v = value[k]
if (v !== undefined && v !== null) {
c[k] = v
}
return c
}, {}),
}
} else {
currentConfig[key] = value
2020-05-22 18:46:36 +02:00
}
return currentConfig
2020-05-22 18:46:36 +02:00
},
{}
)
const result = { ...defaultConfig, ...config }
if (typeof result.assetPrefix !== 'string') {
throw new Error(
`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://err.sh/vercel/next.js/invalid-assetprefix`
)
}
if (typeof result.basePath !== 'string') {
throw new Error(
`Specified basePath is not a string, found type "${typeof result.basePath}"`
)
}
if (result.basePath !== '') {
if (result.basePath === '/') {
throw new Error(
`Specified basePath /. basePath has to be either an empty string or a path prefix"`
)
}
if (!result.basePath.startsWith('/')) {
throw new Error(
`Specified basePath has to start with a /, found "${result.basePath}"`
)
}
if (result.basePath !== '/') {
if (result.basePath.endsWith('/')) {
throw new Error(
`Specified basePath should not end with /, found "${result.basePath}"`
)
}
if (result.assetPrefix === '') {
result.assetPrefix = result.basePath
}
if (result.amp.canonicalBase === '') {
result.amp.canonicalBase = result.basePath
}
}
}
if (result?.images) {
const { images } = result
// Normalize defined image host to end in slash
if (images?.path) {
if (images.path[images.path.length - 1] !== '/') {
images.path += '/'
}
}
if (typeof images !== 'object') {
throw new Error(
`Specified images should be an object received ${typeof images}`
)
}
if (images.domains) {
if (!Array.isArray(images.domains)) {
throw new Error(
`Specified images.domains should be an Array received ${typeof images.domains}`
)
}
if (images.domains.length > 50) {
throw new Error(
`Specified images.domains exceeds length of 50, received length (${images.domains.length}), please reduce the length of the array to continue`
)
}
const invalid = images.domains.filter(
(d: unknown) => typeof d !== 'string'
)
if (invalid.length > 0) {
throw new Error(
`Specified images.domains should be an Array of strings received invalid values (${invalid.join(
', '
)})`
)
}
}
if (images.deviceSizes) {
const { deviceSizes } = images
if (!Array.isArray(deviceSizes)) {
throw new Error(
`Specified images.deviceSizes should be an Array received ${typeof deviceSizes}`
)
}
if (deviceSizes.length > 25) {
throw new Error(
`Specified images.deviceSizes exceeds length of 25, received length (${deviceSizes.length}), please reduce the length of the array to continue`
)
}
const invalid = deviceSizes.filter((d: unknown) => {
return typeof d !== 'number' || d < 1 || d > 10000
})
if (invalid.length > 0) {
throw new Error(
`Specified images.deviceSizes should be an Array of numbers that are between 1 and 10000, received invalid values (${invalid.join(
', '
)})`
)
}
}
if (images.iconSizes) {
const { iconSizes } = images
if (!Array.isArray(iconSizes)) {
throw new Error(
`Specified images.iconSizes should be an Array received ${typeof iconSizes}`
)
}
if (iconSizes.length > 25) {
throw new Error(
`Specified images.iconSizes exceeds length of 25, received length (${iconSizes.length}), please reduce the length of the array to continue`
)
}
const invalid = iconSizes.filter((d: unknown) => {
return typeof d !== 'number' || d < 1 || d > 10000
})
if (invalid.length > 0) {
throw new Error(
`Specified images.iconSizes should be an Array of numbers that are between 1 and 10000, received invalid values (${invalid.join(
', '
)})`
)
}
}
}
if (result.experimental?.i18n) {
const { i18n } = result.experimental
const i18nType = typeof i18n
if (i18nType !== 'object') {
throw new Error(`Specified i18n should be an object received ${i18nType}`)
}
if (!Array.isArray(i18n.locales)) {
throw new Error(
`Specified i18n.locales should be an Array received ${typeof i18n.locales}`
)
}
const defaultLocaleType = typeof i18n.defaultLocale
if (!i18n.defaultLocale || defaultLocaleType !== 'string') {
throw new Error(`Specified i18n.defaultLocale should be a string`)
}
if (typeof i18n.domains !== 'undefined' && !Array.isArray(i18n.domains)) {
throw new Error(
`Specified i18n.domains must be an array of domain objects e.g. [ { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] } ] received ${typeof i18n.domains}`
)
}
if (i18n.domains) {
const invalidDomainItems = i18n.domains.filter((item: any) => {
if (!item || typeof item !== 'object') return true
if (!item.defaultLocale) return true
if (!item.domain || typeof item.domain !== 'string') return true
let hasInvalidLocale = false
if (Array.isArray(item.locales)) {
for (const locale of item.locales) {
if (typeof locale !== 'string') hasInvalidLocale = true
for (const domainItem of i18n.domains) {
if (domainItem === item) continue
if (domainItem.locales && domainItem.locales.includes(locale)) {
console.warn(
`Both ${item.domain} and ${domainItem.domain} configured the locale (${locale}) but only one can. Remove it from one i18n.domains config to continue`
)
hasInvalidLocale = true
break
}
}
}
}
return hasInvalidLocale
})
if (invalidDomainItems.length > 0) {
throw new Error(
`Invalid i18n.domains values:\n${invalidDomainItems
.map((item: any) => JSON.stringify(item))
.join(
'\n'
)}\n\ndomains value must follow format { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] }`
)
}
}
if (!Array.isArray(i18n.locales)) {
throw new Error(
`Specified i18n.locales must be an array of locale strings e.g. ["en-US", "nl-NL"] received ${typeof i18n.locales}`
)
}
const invalidLocales = i18n.locales.filter(
(locale: any) => typeof locale !== 'string'
)
if (invalidLocales.length > 0) {
throw new Error(
`Specified i18n.locales contains invalid values, locales must be valid locale tags provided as strings e.g. "en-US".\n` +
`See here for list of valid language sub-tags: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry`
)
}
if (!i18n.locales.includes(i18n.defaultLocale)) {
throw new Error(
`Specified i18n.defaultLocale should be included in i18n.locales`
)
}
// make sure default Locale is at the front
i18n.locales = [
i18n.defaultLocale,
...i18n.locales.filter((locale: string) => locale !== i18n.defaultLocale),
]
const localeDetectionType = typeof i18n.locales.localeDetection
if (
localeDetectionType !== 'boolean' &&
localeDetectionType !== 'undefined'
) {
throw new Error(
`Specified i18n.localeDetection should be undefined or a boolean received ${localeDetectionType}`
)
}
}
return result
}
export function normalizeConfig(phase: string, config: any) {
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
if (typeof config === 'function') {
config = config(phase, { defaultConfig })
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
if (typeof config.then === 'function') {
throw new Error(
'> Promise returned in next config. https://err.sh/vercel/next.js/promise-in-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 11:39:12 +01:00
return config
}
2016-10-28 16:38:24 +02:00
export default function loadConfig(
phase: string,
dir: string,
customConfig?: object | null
) {
if (customConfig) {
return assignDefaults({ configOrigin: 'server', ...customConfig })
}
const path = findUp.sync(CONFIG_FILE, {
cwd: dir,
})
2016-10-28 16:38:24 +02:00
// If config file was found
if (path?.length) {
const userConfigModule = require(path)
const userConfig = normalizeConfig(
phase,
userConfigModule.default || userConfigModule
)
if (Object.keys(userConfig).length === 0) {
Log.warn(
'Detected next.config.js, no exported configuration found. https://err.sh/vercel/next.js/empty-configuration'
)
}
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
if (userConfig.target && !targets.includes(userConfig.target)) {
throw new Error(
`Specified target is invalid. Provided: "${
userConfig.target
}" should be one of ${targets.join(', ')}`
)
}
if (userConfig.amp?.canonicalBase) {
const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {}
userConfig.amp.canonicalBase =
(canonicalBase.endsWith('/')
? canonicalBase.slice(0, -1)
: canonicalBase) || ''
}
if (
userConfig.experimental?.reactMode &&
!reactModes.includes(userConfig.experimental.reactMode)
) {
throw new Error(
`Specified React Mode is invalid. Provided: ${
userConfig.experimental.reactMode
} should be one of ${reactModes.join(', ')}`
)
}
return assignDefaults({
configOrigin: CONFIG_FILE,
configFile: path,
...userConfig,
})
} else {
const configBaseName = basename(CONFIG_FILE, extname(CONFIG_FILE))
const nonJsPath = findUp.sync(
[
`${configBaseName}.jsx`,
`${configBaseName}.ts`,
`${configBaseName}.tsx`,
`${configBaseName}.json`,
],
{ cwd: dir }
)
if (nonJsPath?.length) {
throw new Error(
`Configuring Next.js via '${basename(
nonJsPath
)}' is not supported. Please replace the file with 'next.config.js'.`
)
}
}
return defaultConfig
2016-10-28 16:38:24 +02:00
}
export function isTargetLikeServerless(target: string) {
const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
return isServerless || isServerlessTrace
}