Unverified Commit e0cc9cd4 authored by Ethan Arrowood's avatar Ethan Arrowood Committed by GitHub

feat(experimental): option to polyfill `fetch` using `undici` in Node.js <18 (#40318)

This PR adds a new `experimental.enableUndici` option to let the
developer switch from `next-fetch` to `undici` as the underlying
polyfill for `fetch` in Node.js.

In the current implementation, Next.js makes sure that `fetch` is always
available by using `node-fetch`. However, we do not polyfill in Node.js
18+, since those versions come with their own `fetch` implementation
already, built-in.

Node.js 18+ uses `undici` under the hood, so letting the developer use
`undici` earlier could make the migration easier later on.

Eventually, we hope to be able to stop polyfilling `fetch` in an
upcoming major version of Next.js, shipping less code.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarBalázs Orbán <info@balazsorban.com>
Co-authored-by: 's avatarSukka <isukkaw@gmail.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent bc685142
...@@ -3,6 +3,7 @@ const nextJest = require('next/jest') ...@@ -3,6 +3,7 @@ const nextJest = require('next/jest')
const createJestConfig = nextJest() const createJestConfig = nextJest()
// Any custom config you want to pass to Jest // Any custom config you want to pass to Jest
/** @type {import('jest').Config} */
const customJestConfig = { const customJestConfig = {
testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.tsx'], testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.tsx'],
setupFilesAfterEnv: ['<rootDir>/jest-setup-after-env.ts'], setupFilesAfterEnv: ['<rootDir>/jest-setup-after-env.ts'],
...@@ -10,6 +11,9 @@ const customJestConfig = { ...@@ -10,6 +11,9 @@ const customJestConfig = {
rootDir: 'test', rootDir: 'test',
modulePaths: ['<rootDir>/lib'], modulePaths: ['<rootDir>/lib'],
transformIgnorePatterns: ['/next[/\\\\]dist/', '/\\.next/'], transformIgnorePatterns: ['/next[/\\\\]dist/', '/\\.next/'],
globals: {
AbortSignal: global.AbortSignal,
},
} }
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async // createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async
......
...@@ -1205,6 +1205,7 @@ export default async function build( ...@@ -1205,6 +1205,7 @@ export default async function build(
configFileName, configFileName,
runtimeEnvConfig, runtimeEnvConfig,
httpAgentOptions: config.httpAgentOptions, httpAgentOptions: config.httpAgentOptions,
enableUndici: config.experimental.enableUndici,
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
pageRuntime: config.experimental.runtime, pageRuntime: config.experimental.runtime,
...@@ -1352,6 +1353,7 @@ export default async function build( ...@@ -1352,6 +1353,7 @@ export default async function build(
configFileName, configFileName,
runtimeEnvConfig, runtimeEnvConfig,
httpAgentOptions: config.httpAgentOptions, httpAgentOptions: config.httpAgentOptions,
enableUndici: config.experimental.enableUndici,
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
parentId: isPageStaticSpan.id, parentId: isPageStaticSpan.id,
......
...@@ -41,7 +41,7 @@ import { ...@@ -41,7 +41,7 @@ import {
LoadComponentsReturnType, LoadComponentsReturnType,
} from '../server/load-components' } from '../server/load-components'
import { trace } from '../trace' import { trace } from '../trace'
import { setHttpAgentOptions } from '../server/config' import { setHttpClientAndAgentOptions } from '../server/config'
import { recursiveDelete } from '../lib/recursive-delete' import { recursiveDelete } from '../lib/recursive-delete'
import { Sema } from 'next/dist/compiled/async-sema' import { Sema } from 'next/dist/compiled/async-sema'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
...@@ -1169,6 +1169,7 @@ export async function isPageStatic({ ...@@ -1169,6 +1169,7 @@ export async function isPageStatic({
configFileName, configFileName,
runtimeEnvConfig, runtimeEnvConfig,
httpAgentOptions, httpAgentOptions,
enableUndici,
locales, locales,
defaultLocale, defaultLocale,
parentId, parentId,
...@@ -1184,6 +1185,7 @@ export async function isPageStatic({ ...@@ -1184,6 +1185,7 @@ export async function isPageStatic({
configFileName: string configFileName: string
runtimeEnvConfig: any runtimeEnvConfig: any
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
enableUndici?: NextConfigComplete['experimental']['enableUndici']
locales?: string[] locales?: string[]
defaultLocale?: string defaultLocale?: string
parentId?: any parentId?: any
...@@ -1210,7 +1212,10 @@ export async function isPageStatic({ ...@@ -1210,7 +1212,10 @@ export async function isPageStatic({
return isPageStaticSpan return isPageStaticSpan
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig) require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
setHttpAgentOptions(httpAgentOptions) setHttpClientAndAgentOptions({
httpAgentOptions,
experimental: { enableUndici },
})
let componentsResult: LoadComponentsReturnType let componentsResult: LoadComponentsReturnType
let prerenderRoutes: Array<string> | undefined let prerenderRoutes: Array<string> | undefined
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
MIT License
Copyright (c) Matteo Collina and Undici contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This source diff could not be displayed because it is too large. You can view the blob instead.
{"name":"undici","main":"index.js","author":"Matteo Collina <hello@matteocollina.com>","license":"MIT"}
...@@ -619,6 +619,7 @@ export default async function exportApp( ...@@ -619,6 +619,7 @@ export default async function exportApp(
httpAgentOptions: nextConfig.httpAgentOptions, httpAgentOptions: nextConfig.httpAgentOptions,
serverComponents: !!nextConfig.experimental.appDir, serverComponents: !!nextConfig.experimental.appDir,
appPaths: options.appPaths || [], appPaths: options.appPaths || [],
enableUndici: nextConfig.experimental.enableUndici,
}) })
for (const validation of result.ampValidations || []) { for (const validation of result.ampValidations || []) {
......
...@@ -23,7 +23,7 @@ import { requireFontManifest } from '../server/require' ...@@ -23,7 +23,7 @@ import { requireFontManifest } from '../server/require'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace' import { trace } from '../trace'
import { isInAmpMode } from '../shared/lib/amp-mode' import { isInAmpMode } from '../shared/lib/amp-mode'
import { setHttpAgentOptions } from '../server/config' import { setHttpClientAndAgentOptions } from '../server/config'
import RenderResult from '../server/render-result' import RenderResult from '../server/render-result'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta' import { addRequestMeta } from '../server/request-meta'
...@@ -70,6 +70,7 @@ interface ExportPageInput { ...@@ -70,6 +70,7 @@ interface ExportPageInput {
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
serverComponents?: boolean serverComponents?: boolean
appPaths: string[] appPaths: string[]
enableUndici: NextConfigComplete['experimental']['enableUndici']
} }
interface ExportPageResults { interface ExportPageResults {
...@@ -119,8 +120,12 @@ export default async function exportPage({ ...@@ -119,8 +120,12 @@ export default async function exportPage({
disableOptimizedLoading, disableOptimizedLoading,
httpAgentOptions, httpAgentOptions,
serverComponents, serverComponents,
enableUndici,
}: ExportPageInput): Promise<ExportPageResults> { }: ExportPageInput): Promise<ExportPageResults> {
setHttpAgentOptions(httpAgentOptions) setHttpClientAndAgentOptions({
httpAgentOptions,
experimental: { enableUndici },
})
const exportPageSpan = trace('export-page-worker', parentSpanId) const exportPageSpan = trace('export-page-worker', parentSpanId)
return exportPageSpan.traceAsyncFn(async () => { return exportPageSpan.traceAsyncFn(async () => {
......
...@@ -264,6 +264,7 @@ ...@@ -264,6 +264,7 @@
"timers-browserify": "2.0.12", "timers-browserify": "2.0.12",
"tty-browserify": "0.0.1", "tty-browserify": "0.0.1",
"ua-parser-js": "0.7.28", "ua-parser-js": "0.7.28",
"undici": "5.10.0",
"unistore": "3.4.1", "unistore": "3.4.1",
"util": "0.12.4", "util": "0.12.4",
"uuid": "8.3.2", "uuid": "8.3.2",
......
...@@ -390,6 +390,9 @@ const configSchema = { ...@@ -390,6 +390,9 @@ const configSchema = {
}, },
type: 'array', type: 'array',
}, },
enableUndici: {
type: 'boolean',
},
workerThreads: { workerThreads: {
type: 'boolean', type: 'boolean',
}, },
......
...@@ -146,6 +146,7 @@ export interface ExperimentalConfig { ...@@ -146,6 +146,7 @@ export interface ExperimentalConfig {
* [webpack/webpack#ModuleNotoundError.js#L13-L42](https://github.com/webpack/webpack/blob/2a0536cf510768111a3a6dceeb14cb79b9f59273/lib/ModuleNotFoundError.js#L13-L42) * [webpack/webpack#ModuleNotoundError.js#L13-L42](https://github.com/webpack/webpack/blob/2a0536cf510768111a3a6dceeb14cb79b9f59273/lib/ModuleNotFoundError.js#L13-L42)
*/ */
fallbackNodePolyfills?: false fallbackNodePolyfills?: false
enableUndici?: boolean
sri?: { sri?: {
algorithm?: SubresourceIntegrityAlgorithm algorithm?: SubresourceIntegrityAlgorithm
} }
...@@ -585,6 +586,7 @@ export const defaultConfig: NextConfig = { ...@@ -585,6 +586,7 @@ export const defaultConfig: NextConfig = {
amp: undefined, amp: undefined,
urlImports: undefined, urlImports: undefined,
modularizeImports: undefined, modularizeImports: undefined,
enableUndici: false,
adjustFontFallbacks: false, adjustFontFallbacks: false,
}, },
} }
......
...@@ -139,6 +139,7 @@ export function loadWebpackHook() { ...@@ -139,6 +139,7 @@ export function loadWebpackHook() {
'next/dist/compiled/@babel/runtime/package.json', 'next/dist/compiled/@babel/runtime/package.json',
], ],
['node-fetch', 'next/dist/compiled/node-fetch'], ['node-fetch', 'next/dist/compiled/node-fetch'],
['undici', 'next/dist/compiled/undici'],
].map( ].map(
// Use dynamic require.resolve to avoid statically analyzable since they're only for build time // Use dynamic require.resolve to avoid statically analyzable since they're only for build time
([request, replacement]) => [request, require.resolve(replacement)] ([request, replacement]) => [request, require.resolve(replacement)]
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
ExperimentalConfig, ExperimentalConfig,
NextConfigComplete, NextConfigComplete,
validateConfig, validateConfig,
NextConfig,
} from './config-shared' } from './config-shared'
import { loadWebpackHook } from './config-utils' import { loadWebpackHook } from './config-utils'
import { import {
...@@ -22,6 +23,7 @@ import { ...@@ -22,6 +23,7 @@ import {
} from '../shared/lib/image-config' } from '../shared/lib/image-config'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { hasNextSupport } from '../telemetry/ci-info' import { hasNextSupport } from '../telemetry/ci-info'
import { gte as semverGte } from 'next/dist/compiled/semver'
export { DomainLocale, NextConfig, normalizeConfig } from './config-shared' export { DomainLocale, NextConfig, normalizeConfig } from './config-shared'
...@@ -45,12 +47,22 @@ const experimentalWarning = execOnce( ...@@ -45,12 +47,22 @@ const experimentalWarning = execOnce(
} }
) )
export function setHttpAgentOptions( export function setHttpClientAndAgentOptions(options: NextConfig) {
options: NextConfigComplete['httpAgentOptions'] if (semverGte(process.version, '16.8.0')) {
) { if (semverGte(process.version, '18.0.0')) {
Log.warn(
'`enableUndici` option is unnecessary in Node.js v18.0.0 or greater.'
)
}
;(global as any).__NEXT_USE_UNDICI = options.experimental?.enableUndici
} else if (options.experimental?.enableUndici) {
Log.warn(
'`enableUndici` option requires Node.js v16.8.0 or greater. Falling back to `node-fetch`'
)
}
if ((global as any).__NEXT_HTTP_AGENT) { if ((global as any).__NEXT_HTTP_AGENT) {
// We only need to assign once because we want // We only need to assign once because we want
// to resuse the same agent for all requests. // to reuse the same agent for all requests.
return return
} }
...@@ -58,8 +70,9 @@ export function setHttpAgentOptions( ...@@ -58,8 +70,9 @@ export function setHttpAgentOptions(
throw new Error('Expected config.httpAgentOptions to be an object') throw new Error('Expected config.httpAgentOptions to be an object')
} }
;(global as any).__NEXT_HTTP_AGENT = new HttpAgent(options) ;(global as any).__NEXT_HTTP_AGENT_OPTIONS = options.httpAgentOptions
;(global as any).__NEXT_HTTPS_AGENT = new HttpsAgent(options) ;(global as any).__NEXT_HTTP_AGENT = new HttpAgent(options.httpAgentOptions)
;(global as any).__NEXT_HTTPS_AGENT = new HttpsAgent(options.httpAgentOptions)
} }
function assignDefaults(userConfig: { [key: string]: any }) { function assignDefaults(userConfig: { [key: string]: any }) {
...@@ -545,9 +558,7 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -545,9 +558,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
// TODO: Change defaultConfig type to NextConfigComplete // TODO: Change defaultConfig type to NextConfigComplete
// so we don't need "!" here. // so we don't need "!" here.
setHttpAgentOptions( setHttpClientAndAgentOptions(result || defaultConfig)
result.httpAgentOptions || defaultConfig.httpAgentOptions!
)
if (result.i18n) { if (result.i18n) {
const { i18n } = result const { i18n } = result
...@@ -855,6 +866,6 @@ export default async function loadConfig( ...@@ -855,6 +866,6 @@ export default async function loadConfig(
// reactRoot can be updated correctly even with no next.config.js // reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults(defaultConfig) as NextConfigComplete const completeConfig = assignDefaults(defaultConfig) as NextConfigComplete
completeConfig.configFileName = configFileName completeConfig.configFileName = configFileName
setHttpAgentOptions(completeConfig.httpAgentOptions) setHttpClientAndAgentOptions(completeConfig)
return completeConfig return completeConfig
} }
...@@ -1286,6 +1286,7 @@ export default class DevServer extends Server { ...@@ -1286,6 +1286,7 @@ export default class DevServer extends Server {
publicRuntimeConfig, publicRuntimeConfig,
serverRuntimeConfig, serverRuntimeConfig,
httpAgentOptions, httpAgentOptions,
experimental: { enableUndici },
} = this.nextConfig } = this.nextConfig
const { locales, defaultLocale } = this.nextConfig.i18n || {} const { locales, defaultLocale } = this.nextConfig.i18n || {}
...@@ -1299,6 +1300,7 @@ export default class DevServer extends Server { ...@@ -1299,6 +1300,7 @@ export default class DevServer extends Server {
serverRuntimeConfig, serverRuntimeConfig,
}, },
httpAgentOptions, httpAgentOptions,
enableUndici,
locales, locales,
defaultLocale, defaultLocale,
originalAppPath, originalAppPath,
......
...@@ -7,7 +7,7 @@ import { ...@@ -7,7 +7,7 @@ import {
collectGenerateParams, collectGenerateParams,
} from '../../build/utils' } from '../../build/utils'
import { loadComponents } from '../load-components' import { loadComponents } from '../load-components'
import { setHttpAgentOptions } from '../config' import { setHttpClientAndAgentOptions } from '../config'
type RuntimeConfig = any type RuntimeConfig = any
...@@ -22,6 +22,7 @@ export async function loadStaticPaths({ ...@@ -22,6 +22,7 @@ export async function loadStaticPaths({
serverless, serverless,
config, config,
httpAgentOptions, httpAgentOptions,
enableUndici,
locales, locales,
defaultLocale, defaultLocale,
isAppPath, isAppPath,
...@@ -32,6 +33,7 @@ export async function loadStaticPaths({ ...@@ -32,6 +33,7 @@ export async function loadStaticPaths({
serverless: boolean serverless: boolean
config: RuntimeConfig config: RuntimeConfig
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
enableUndici: NextConfigComplete['enableUndici']
locales?: string[] locales?: string[]
defaultLocale?: string defaultLocale?: string
isAppPath?: boolean isAppPath?: boolean
...@@ -49,7 +51,10 @@ export async function loadStaticPaths({ ...@@ -49,7 +51,10 @@ export async function loadStaticPaths({
// update work memory runtime-config // update work memory runtime-config
require('../../shared/lib/runtime-config').setConfig(config) require('../../shared/lib/runtime-config').setConfig(config)
setHttpAgentOptions(httpAgentOptions) setHttpClientAndAgentOptions({
httpAgentOptions,
experimental: { enableUndici },
})
const components = await loadComponents({ const components = await loadComponents({
distDir, distDir,
......
import fetch, {
Headers,
Request,
Response,
} from 'next/dist/compiled/node-fetch'
// Polyfill fetch() in the Node.js environment // Polyfill fetch() in the Node.js environment
if (!global.fetch) { if (!global.fetch) {
const agent = ({ protocol }) => function getFetchImpl() {
protocol === 'http:' ? global.__NEXT_HTTP_AGENT : global.__NEXT_HTTPS_AGENT return global.__NEXT_USE_UNDICI
const fetchWithAgent = (url, opts, ...rest) => { ? require('next/dist/compiled/undici')
if (!opts) { : require('next/dist/compiled/node-fetch')
opts = { agent } }
} else if (!opts.agent) { // Due to limitation of global configuration, we have to do this resolution at runtime
opts.agent = agent global.fetch = (...args) => {
const fetchImpl = getFetchImpl()
if (global.__NEXT_USE_UNDICI) {
// Undici does not support the `keepAlive` option,
// instead we have to pass a custom dispatcher
if (
!global.__NEXT_HTTP_AGENT_OPTIONS?.keepAlive &&
!global.__NEXT_UNDICI_AGENT_SET
) {
global.__NEXT_UNDICI_AGENT_SET = true
fetchImpl.setGlobalDispatcher(new fetchImpl.Agent({ pipelining: 0 }))
}
return fetchImpl.fetch(...args)
} }
return fetch(url, opts, ...rest) const agent = ({ protocol }) =>
protocol === 'http:'
? global.__NEXT_HTTP_AGENT
: global.__NEXT_HTTPS_AGENT
if (!args[1]) {
args[1] = { agent }
} else if (!args[1].agent) {
args[1].agent = agent
}
return fetchImpl(...args)
} }
global.fetch = fetchWithAgent
global.Headers = Headers Object.defineProperties(global, {
global.Request = Request Headers: {
global.Response = Response get() {
return getFetchImpl().Headers
},
},
Request: {
get() {
return getFetchImpl().Request
},
},
Response: {
get() {
return getFetchImpl().Response
},
},
})
} }
...@@ -86,6 +86,8 @@ const externals = { ...@@ -86,6 +86,8 @@ const externals = {
'next/dist/build/webpack/plugins/terser-webpack-plugin', 'next/dist/build/webpack/plugins/terser-webpack-plugin',
// TODO: Add @swc/helpers to externals once @vercel/ncc switch to swc-loader // TODO: Add @swc/helpers to externals once @vercel/ncc switch to swc-loader
undici: 'undici',
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['node-html-parser'] = 'next/dist/compiled/node-html-parser' externals['node-html-parser'] = 'next/dist/compiled/node-html-parser'
...@@ -167,6 +169,14 @@ export async function ncc_node_fetch(task, opts) { ...@@ -167,6 +169,14 @@ export async function ncc_node_fetch(task, opts) {
.target('compiled/node-fetch') .target('compiled/node-fetch')
} }
externals['undici'] = 'next/dist/compiled/undici'
export async function ncc_undici(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('undici')))
.ncc({ packageName: 'undici', externals })
.target('compiled/undici')
}
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function compile_config_schema(task, opts) { export async function compile_config_schema(task, opts) {
const { configSchema } = require('./dist/server/config-schema') const { configSchema } = require('./dist/server/config-schema')
...@@ -1818,6 +1828,7 @@ export async function ncc(task, opts) { ...@@ -1818,6 +1828,7 @@ export async function ncc(task, opts) {
'ncc_get_orientation', 'ncc_get_orientation',
'ncc_hapi_accept', 'ncc_hapi_accept',
'ncc_node_fetch', 'ncc_node_fetch',
'ncc_undici',
'ncc_acorn', 'ncc_acorn',
'ncc_amphtml_validator', 'ncc_amphtml_validator',
'ncc_arg', 'ncc_arg',
......
...@@ -28,6 +28,8 @@ declare module 'next/dist/compiled/node-fetch' { ...@@ -28,6 +28,8 @@ declare module 'next/dist/compiled/node-fetch' {
export * from 'node-fetch' export * from 'node-fetch'
} }
declare module 'next/dist/compiled/undici' {}
declare module 'next/dist/compiled/jest-worker' { declare module 'next/dist/compiled/jest-worker' {
export * from 'jest-worker' export * from 'jest-worker'
} }
......
This diff is collapsed.
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils'
import semver from 'semver'
if (
semver.lt(process.version, '16.8.0') ||
semver.gte(process.version, '18.0.0')
) {
it('skipping for Node.js versions <16.8.0 and >18.0.0', () => {
expect(true).toBe(true)
})
} else {
describe('undici fetch', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/api/globalFetch.js': `
import { ReadableStream } from 'node:stream/web';
export default async function globalFetch(req, res) {
try {
const response = await fetch('https://example.vercel.sh')
res.json({ value: response.body instanceof ReadableStream })
} catch (error) {
console.error(error);
res.send(error);
}
}
`,
'pages/api/globalHeaders.js': `
export default async function globalHeaders(req, res) {
res.json({
value: (new Headers())[Symbol.iterator].name === 'entries'
})
}
`,
'pages/api/globalRequest.js': `
export default async function globalRequest(req, res) {
res.json({
value: (new Request('https://example.vercel.sh')).headers[Symbol.iterator].name === 'entries'
})
}
`,
'pages/api/globalResponse.js': `
export default async function globalResponse(req, res) {
res.json({
value: (new Response()).headers[Symbol.iterator].name === 'entries'
})
}
`,
},
dependencies: {},
nextConfig: {
experimental: {
enableUndici: true,
},
},
})
})
afterAll(() => next.destroy())
describe('undici', () => {
it('global fetch should return true when undici is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalFetch')
const data = await result.json()
expect(data.value).toBe(true)
})
it('global Headers should return true when undici is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalHeaders')
const data = await result.json()
expect(data.value).toBe(true)
})
it('global Request should return true when undici is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalRequest')
const data = await result.json()
expect(data.value).toBe(true)
})
it('global Response should return true when undici is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalResponse')
const data = await result.json()
expect(data.value).toBe(true)
})
})
describe('node-fetch', () => {
beforeAll(async () => {
await next.stop()
await next.patchFile(
'next.config.js',
`module.exports = ${JSON.stringify({
experimental: {
enableUndici: false,
},
})}`
)
await next.start()
})
it('global fetch should return false when node-fetch is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalFetch')
const data = await result.json()
expect(data.value).toBe(false)
})
it('global Headers should return false when node-fetch is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalHeaders')
const data = await result.json()
expect(data.value).toBe(false)
})
it('global Request should return false when node-fetch is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalRequest')
const data = await result.json()
expect(data.value).toBe(false)
})
it('global Response should return false when node-fetch is used', async () => {
const result = await fetchViaHTTP(next.url, '/api/globalResponse')
const data = await result.json()
expect(data.value).toBe(false)
})
})
})
}
module.exports = {
experimental: {
enableUndici: true,
},
}
export default async function handler(_req, res) {
const fetchRes = await fetch('http://localhost:44001')
const props = await fetchRes.json()
res.json(props)
}
export default function Blog(props) {
return <pre id="props">{JSON.stringify(props)}</pre>
}
export async function getStaticProps({ params: { slug } }) {
return { props: { slug } }
}
export async function getStaticPaths() {
const res = await fetch('http://localhost:44001')
const obj = await res.json()
if (obj.connection === 'keep-alive') {
return {
paths: [{ params: { slug: 'first' } }],
fallback: false,
}
}
return {
paths: [],
fallback: false,
}
}
export default function SSG(props) {
return <pre id="props">{JSON.stringify(props)}</pre>
}
export async function getStaticProps() {
const res = await fetch('http://localhost:44001')
const props = await res.json()
return { props }
}
export default function SSR(props) {
return <pre id="props">{JSON.stringify(props)}</pre>
}
export async function getServerSideProps() {
const res = await fetch('http://localhost:44001')
const props = await res.json()
return { props }
}
/* eslint-env jest */
import { join } from 'path'
import { createServer } from 'http'
import {
fetchViaHTTP,
nextBuild,
findPort,
nextStart,
launchApp,
killApp,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../')
let appPort
let app
let mockServer
describe('undici-keep-alive', () => {
describe('dev', () => {
beforeAll(async () => {
mockServer = createServer((req, res) => {
// we can test request headers by sending them
// back with the response
const { connection } = req.headers
res.end(JSON.stringify({ connection }))
})
mockServer.listen(44001)
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
mockServer.close()
})
runTests()
})
describe('production', () => {
beforeAll(async () => {
mockServer = createServer((req, res) => {
// we can test request headers by sending them
// back with the response
const { connection } = req.headers
res.end(JSON.stringify({ connection }))
})
mockServer.listen(44001)
const { stdout, stderr } = await nextBuild(appDir, [], {
stdout: true,
stderr: true,
})
if (stdout) console.log(stdout)
if (stderr) console.error(stderr)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
mockServer.close()
})
runTests()
})
function runTests() {
it('should send keep-alive for json API', async () => {
const res = await fetchViaHTTP(appPort, '/api/json')
const obj = await res.json()
expect(obj).toEqual({ connection: 'keep-alive' })
})
it('should send keep-alive for getStaticProps', async () => {
const browser = await webdriver(appPort, '/ssg')
const props = await browser.elementById('props').text()
const obj = JSON.parse(props)
expect(obj).toEqual({ connection: 'keep-alive' })
await browser.close()
})
it('should send keep-alive for getStaticPaths', async () => {
const browser = await webdriver(appPort, '/blog/first')
const props = await browser.elementById('props').text()
const obj = JSON.parse(props)
expect(obj).toEqual({ slug: 'first' })
await browser.close()
})
it('should send keep-alive for getServerSideProps', async () => {
const browser = await webdriver(appPort, '/ssr')
const props = await browser.elementById('props').text()
const obj = JSON.parse(props)
expect(obj).toEqual({ connection: 'keep-alive' })
await browser.close()
})
}
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment