Skip to content

Commit

Permalink
Ensure undefined values end up being replaced (#63138)
Browse files Browse the repository at this point in the history
## What?

Follow-up to #63128

`JSON.stringify(undefined)` ends up with the value `undefined`. However
for Webpack/Turbopack to correctly inject `undefined` into the code it
has to be the string `'undefined'`. This change ensures the
serialization takes into account that case.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-2773
  • Loading branch information
timneutkens authored Mar 12, 2024
1 parent 7de0f47 commit 54adb71
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 62 deletions.
7 changes: 3 additions & 4 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,15 +1351,14 @@ export default async function build(
env: process.env as Record<string, string>,
defineEnv: createDefineEnv({
isTurbopack: true,
allowedRevalidateHeaderKeys: undefined,
clientRouterFilters: undefined,
clientRouterFilters: NextBuildContext.clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix: undefined,
fetchCacheKeyPrefix: config.experimental.fetchCacheKeyPrefix,
hasRewrites,
// TODO: Implement
middlewareMatchers: undefined,
previewModeId: undefined,
}),
})

Expand Down
4 changes: 0 additions & 4 deletions packages/next/src/build/swc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,15 +435,13 @@ export interface DefineEnv {

export function createDefineEnv({
isTurbopack,
allowedRevalidateHeaderKeys,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
middlewareMatchers,
previewModeId,
}: Omit<
DefineEnvPluginOptions,
'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer'
Expand All @@ -458,7 +456,6 @@ export function createDefineEnv({
defineEnv[variant] = rustifyEnv(
getDefineEnv({
isTurbopack,
allowedRevalidateHeaderKeys,
clientRouterFilters,
config,
dev,
Expand All @@ -470,7 +467,6 @@ export function createDefineEnv({
isNodeOrEdgeCompilation: variant === 'nodejs' || variant === 'edge',
isNodeServer: variant === 'nodejs',
middlewareMatchers,
previewModeId,
})
)
}
Expand Down
6 changes: 0 additions & 6 deletions packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,7 @@ export default async function getBaseWebpackConfig(
resolvedBaseUrl,
supportedBrowsers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
}: {
buildId: string
config: NextConfigComplete
Expand Down Expand Up @@ -348,9 +346,7 @@ export default async function getBaseWebpackConfig(
import('../shared/lib/bloom-filter').BloomFilter['export']
>
}
previewModeId?: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}
): Promise<webpack.Configuration> {
const isClient = compilerType === COMPILER_NAMES.client
Expand Down Expand Up @@ -1741,7 +1737,6 @@ export default async function getBaseWebpackConfig(
}),
getDefineEnvPlugin({
isTurbopack: false,
allowedRevalidateHeaderKeys,
clientRouterFilters,
config,
dev,
Expand All @@ -1753,7 +1748,6 @@ export default async function getBaseWebpackConfig(
isNodeOrEdgeCompilation,
isNodeServer,
middlewareMatchers,
previewModeId,
}),
isClient &&
new ReactLoadablePlugin({
Expand Down
62 changes: 29 additions & 33 deletions packages/next/src/build/webpack/plugins/define-env-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ type BloomFilter = ReturnType<

export interface DefineEnvPluginOptions {
isTurbopack: boolean
allowedRevalidateHeaderKeys: string[] | undefined
clientRouterFilters?: {
staticFilter: BloomFilter
dynamicFilter: BloomFilter
Expand All @@ -38,15 +37,13 @@ export interface DefineEnvPluginOptions {
isNodeOrEdgeCompilation: boolean
isNodeServer: boolean
middlewareMatchers: MiddlewareMatcher[] | undefined
previewModeId: string | undefined
}

interface DefineEnv {
[key: string]:
| string
| string[]
| boolean
| undefined
| MiddlewareMatcher[]
| BloomFilter
| Partial<NextConfigComplete['images']>
Expand Down Expand Up @@ -129,7 +126,6 @@ function getImageConfig(

export function getDefineEnv({
isTurbopack,
allowedRevalidateHeaderKeys,
clientRouterFilters,
config,
dev,
Expand All @@ -141,7 +137,6 @@ export function getDefineEnv({
isNodeOrEdgeCompilation,
isNodeServer,
middlewareMatchers,
previewModeId,
}: DefineEnvPluginOptions): SerializedDefineEnv {
const defineEnv: DefineEnv = {
// internal field to identify the plugin config
Expand All @@ -158,7 +153,7 @@ export function getDefineEnv({
* and library authors to have different implementations based on
* the runtime they are running with, if it's not using `edge-runtime`
*/
process.env.NEXT_EDGE_RUNTIME_PROVIDER || 'edge-runtime',
process.env.NEXT_EDGE_RUNTIME_PROVIDER ?? 'edge-runtime',
}),
'process.turbopack': isTurbopack,
'process.env.TURBOPACK': isTurbopack,
Expand All @@ -172,70 +167,71 @@ export function getDefineEnv({
'process.env.NEXT_MINIMAL': '',
'process.env.__NEXT_PPR': config.experimental.ppr === true,
'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID':
config.experimental.useDeploymentIdServerActions,
'process.env.NEXT_DEPLOYMENT_ID': config.experimental.deploymentId || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix,
'process.env.__NEXT_PREVIEW_MODE_ID': previewModeId,
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':
allowedRevalidateHeaderKeys,
'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers || [],
config.experimental.useDeploymentIdServerActions ?? false,
'process.env.NEXT_DEPLOYMENT_ID': config.experimental.deploymentId ?? false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],
'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':
config.experimental.manualClientBasePath,
config.experimental.manualClientBasePath ?? false,
'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':
config.experimental.clientRouterFilter,
config.experimental.clientRouterFilter ?? true,
'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':
clientRouterFilters?.staticFilter,
clientRouterFilters?.staticFilter ?? false,
'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':
clientRouterFilters?.dynamicFilter,
clientRouterFilters?.dynamicFilter ?? false,
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
config.experimental.optimisticClientCache,
config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH':
config.experimental.middlewarePrefetch,
config.experimental.middlewarePrefetch ?? 'flexible',
'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,
'process.browser': isClient,
'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE,
'process.env.__NEXT_TEST_MODE': process.env.__NEXT_TEST_MODE ?? false,
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...(dev && (isClient || isEdgeServer)
...(dev && (isClient ?? isEdgeServer)
? {
'process.env.__NEXT_DIST_DIR': distDir,
}
: {}),
'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,
'process.env.__NEXT_BUILD_INDICATOR': config.devIndicators.buildActivity,
'process.env.__NEXT_BUILD_INDICATOR':
config.devIndicators.buildActivity ?? true,
'process.env.__NEXT_BUILD_INDICATOR_POSITION':
config.devIndicators.buildActivityPosition,
config.devIndicators.buildActivityPosition ?? 'bottom-right',
'process.env.__NEXT_STRICT_MODE':
config.reactStrictMode === null ? false : config.reactStrictMode,
'process.env.__NEXT_STRICT_MODE_APP':
// When next.config.js does not have reactStrictMode it's enabled by default.
config.reactStrictMode === null ? true : config.reactStrictMode,
'process.env.__NEXT_OPTIMIZE_FONTS': !dev && config.optimizeFonts,
'process.env.__NEXT_OPTIMIZE_CSS': config.experimental.optimizeCss && !dev,
'process.env.__NEXT_OPTIMIZE_CSS':
(config.experimental.optimizeCss && !dev) ?? false,
'process.env.__NEXT_SCRIPT_WORKERS':
config.experimental.nextScriptWorkers && !dev,
(config.experimental.nextScriptWorkers && !dev) ?? false,
'process.env.__NEXT_SCROLL_RESTORATION':
config.experimental.scrollRestoration,
config.experimental.scrollRestoration ?? false,
...getImageConfig(config, dev),
'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,
'process.env.__NEXT_STRICT_NEXT_HEAD': config.experimental.strictNextHead,
'process.env.__NEXT_STRICT_NEXT_HEAD':
config.experimental.strictNextHead ?? false,
'process.env.__NEXT_HAS_REWRITES': hasRewrites,
'process.env.__NEXT_CONFIG_OUTPUT': config.output,
'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,
'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains,
'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,
'process.env.__NEXT_ANALYTICS_ID': config.analyticsId, // TODO: remove in the next major version
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':
config.skipMiddlewareUrlNormalize,
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':
config.experimental.externalMiddlewareRewritesResolve,
config.experimental.externalMiddlewareRewritesResolve ?? false,
'process.env.__NEXT_MANUAL_TRAILING_SLASH':
config.skipTrailingSlashRedirect,
'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION':
config.experimental.webVitalsAttribution &&
config.experimental.webVitalsAttribution.length > 0,
(config.experimental.webVitalsAttribution &&
config.experimental.webVitalsAttribution.length > 0) ??
false,
'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':
config.experimental.webVitalsAttribution,
config.experimental.webVitalsAttribution ?? false,
'process.env.__NEXT_LINK_NO_TOUCH_START':
config.experimental.linkNoTouchStart,
config.experimental.linkNoTouchStart ?? false,
'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,
...(isNodeOrEdgeCompilation
? {
Expand Down
6 changes: 3 additions & 3 deletions packages/next/src/server/dev/hot-reloader-turbopack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,15 @@ export async function createHotReloaderTurbopack(
env: process.env as Record<string, string>,
defineEnv: createDefineEnv({
isTurbopack: true,
allowedRevalidateHeaderKeys: undefined,
// TODO: Implement
clientRouterFilters: undefined,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: undefined,
fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
// TODO: Implement
middlewareMatchers: undefined,
previewModeId: undefined,
}),
})
const entrypointsSubscription = project.entrypointsSubscribe()
Expand Down
11 changes: 5 additions & 6 deletions packages/next/src/server/lib/router-utils/setup-dev-bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,15 +553,15 @@ async function startWatcher(opts: SetupOpts) {
await hotReloader.turbopackProject.update({
defineEnv: createDefineEnv({
isTurbopack: true,
allowedRevalidateHeaderKeys: undefined,
clientRouterFilters,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: undefined,
fetchCacheKeyPrefix:
opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
// TODO: Implement
middlewareMatchers: undefined,
previewModeId: undefined,
}),
})
}
Expand Down Expand Up @@ -625,19 +625,18 @@ async function startWatcher(opts: SetupOpts) {
) {
const newDefine = getDefineEnv({
isTurbopack: false,
allowedRevalidateHeaderKeys: undefined,
clientRouterFilters,
config: nextConfig,
dev: true,
distDir,
fetchCacheKeyPrefix: undefined,
fetchCacheKeyPrefix:
opts.nextConfig.experimental.fetchCacheKeyPrefix,
hasRewrites,
isClient,
isEdgeServer,
isNodeOrEdgeCompilation: isNodeServer || isEdgeServer,
isNodeServer,
middlewareMatchers: undefined,
previewModeId: undefined,
})

Object.keys(plugin.definitions).forEach((key) => {
Expand Down
19 changes: 15 additions & 4 deletions packages/next/src/shared/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -765,13 +765,24 @@ export default class Router implements BaseRouter {
const { BloomFilter } =
require('../../lib/bloom-filter') as typeof import('../../lib/bloom-filter')

const staticFilterData:
| ReturnType<import('../../lib/bloom-filter').BloomFilter['export']>
| undefined = process.env.__NEXT_CLIENT_ROUTER_S_FILTER as any
type Filter = ReturnType<
import('../../lib/bloom-filter').BloomFilter['export']
>

const dynamicFilterData: typeof staticFilterData = process.env
const routerFilterSValue: Filter | false = process.env
.__NEXT_CLIENT_ROUTER_S_FILTER as any

const staticFilterData: Filter | undefined = routerFilterSValue
? routerFilterSValue
: undefined

const routerFilterDValue: Filter | false = process.env
.__NEXT_CLIENT_ROUTER_D_FILTER as any

const dynamicFilterData: Filter | undefined = routerFilterDValue
? routerFilterDValue
: undefined

if (staticFilterData?.numHashes) {
this._bfl_s = new BloomFilter(
staticFilterData.numItems,
Expand Down
2 changes: 0 additions & 2 deletions test/development/basic/next-rs-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,6 @@ describe('next.rs api', () => {
dev: true,
defineEnv: createDefineEnv({
isTurbopack: true,
allowedRevalidateHeaderKeys: undefined,
clientRouterFilters: undefined,
config: nextConfig,
dev: true,
Expand All @@ -218,7 +217,6 @@ describe('next.rs api', () => {
fetchCacheKeyPrefix: undefined,
hasRewrites: false,
middlewareMatchers: undefined,
previewModeId: undefined,
}),
})
projectUpdateSubscription = filterMapAsyncIterator(
Expand Down

0 comments on commit 54adb71

Please sign in to comment.