File size: 14,138 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import type {
  I18NConfig,
  I18NDomains,
  NextConfigComplete,
} from '../server/config-shared'
import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import type { Rewrite } from '../lib/load-custom-routes'
import path from 'node:path'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'
import {
  getNextConfigEnv,
  getNextPublicEnvironmentVariables,
} from '../lib/static-env'

type BloomFilter = ReturnType<
  import('../shared/lib/bloom-filter').BloomFilter['export']
>

export interface DefineEnvOptions {
  isTurbopack: boolean
  clientRouterFilters?: {
    staticFilter: BloomFilter
    dynamicFilter: BloomFilter
  }
  config: NextConfigComplete
  dev: boolean
  distDir: string
  projectPath: string
  fetchCacheKeyPrefix: string | undefined
  hasRewrites: boolean
  isClient: boolean
  isEdgeServer: boolean
  isNodeServer: boolean
  middlewareMatchers: MiddlewareMatcher[] | undefined
  omitNonDeterministic?: boolean
  rewrites: {
    beforeFiles: Rewrite[]
    afterFiles: Rewrite[]
    fallback: Rewrite[]
  }
}

interface DefineEnv {
  [key: string]:
    | string
    | string[]
    | boolean
    | MiddlewareMatcher[]
    | BloomFilter
    | Partial<NextConfigComplete['images']>
    | I18NDomains
    | I18NConfig
}

interface SerializedDefineEnv {
  [key: string]: string
}

/**
 * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.
 */
function serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {
  const defineEnvStringified: SerializedDefineEnv = {}
  for (const key in defineEnv) {
    const value = defineEnv[key]
    defineEnvStringified[key] = JSON.stringify(value)
  }

  return defineEnvStringified
}

function getImageConfig(
  config: NextConfigComplete,
  dev: boolean
): { 'process.env.__NEXT_IMAGE_OPTS': Partial<NextConfigComplete['images']> } {
  return {
    'process.env.__NEXT_IMAGE_OPTS': {
      deviceSizes: config.images.deviceSizes,
      imageSizes: config.images.imageSizes,
      qualities: config.images.qualities,
      path: config.images.path,
      loader: config.images.loader,
      dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
      unoptimized: config?.images?.unoptimized,
      ...(dev
        ? {
            // additional config in dev to allow validating on the client
            domains: config.images.domains,
            remotePatterns: config.images?.remotePatterns,
            localPatterns: config.images?.localPatterns,
            output: config.output,
          }
        : {}),
    },
  }
}

export function getDefineEnv({
  isTurbopack,
  clientRouterFilters,
  config,
  dev,
  distDir,
  projectPath,
  fetchCacheKeyPrefix,
  hasRewrites,
  isClient,
  isEdgeServer,
  isNodeServer,
  middlewareMatchers,
  omitNonDeterministic,
  rewrites,
}: DefineEnvOptions): SerializedDefineEnv {
  const nextPublicEnv = getNextPublicEnvironmentVariables()
  const nextConfigEnv = getNextConfigEnv(config)

  const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
  const isCacheComponentsEnabled = !!config.experimental.cacheComponents
  const isUseCacheEnabled = !!config.experimental.useCache

  const defineEnv: DefineEnv = {
    // internal field to identify the plugin config
    __NEXT_DEFINE_ENV: true,

    ...nextPublicEnv,
    ...nextConfigEnv,
    ...(!isEdgeServer
      ? {}
      : {
          EdgeRuntime:
            /**
             * Cloud providers can set this environment variable to allow users
             * 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 should be only { env: {...} } for edge runtime.
          // For ignore avoid warn on `process.emit` usage but directly omit it.
          'process.emit': false,
        }),
    'process.turbopack': isTurbopack,
    'process.env.TURBOPACK': isTurbopack,
    'process.env.__NEXT_BUNDLER': isTurbopack
      ? 'Turbopack'
      : process.env.NEXT_RSPACK
        ? 'Rspack'
        : 'Webpack',
    // TODO: enforce `NODE_ENV` on `process.env`, and add a test:
    'process.env.NODE_ENV':
      dev || config.experimental.allowDevelopmentBuild
        ? 'development'
        : 'production',
    'process.env.NEXT_RUNTIME': isEdgeServer
      ? 'edge'
      : isNodeServer
        ? 'nodejs'
        : '',
    'process.env.NEXT_MINIMAL': '',
    'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(
      config.experimental.appNavFailHandling
    ),
    'process.env.__NEXT_PPR': isPPREnabled,
    'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
    'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,

    'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
      ? false
      : config.deploymentId || false,
    // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
    // variable to the client.
    'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':
      process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING || false,
    'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
    ...(isTurbopack
      ? {}
      : {
          'process.env.__NEXT_MIDDLEWARE_MATCHERS': middlewareMatchers ?? [],
        }),
    'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH':
      config.experimental.manualClientBasePath ?? false,
    'process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME': JSON.stringify(
      isNaN(Number(config.experimental.staleTimes?.dynamic))
        ? 0
        : config.experimental.staleTimes?.dynamic
    ),
    'process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME': JSON.stringify(
      isNaN(Number(config.experimental.staleTimes?.static))
        ? 5 * 60 // 5 minutes
        : config.experimental.staleTimes?.static
    ),
    'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':
      config.experimental.clientRouterFilter ?? true,
    'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':
      clientRouterFilters?.staticFilter ?? false,
    'process.env.__NEXT_CLIENT_ROUTER_D_FILTER':
      clientRouterFilters?.dynamicFilter ?? false,
    'process.env.__NEXT_CLIENT_SEGMENT_CACHE': Boolean(
      config.experimental.clientSegmentCache
    ),
    'process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS': Boolean(
      config.experimental.validateRSCRequestHeaders
    ),
    'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(
      config.experimental.dynamicOnHover
    ),
    'process.env.__NEXT_ROUTER_BF_CACHE': Boolean(
      config.experimental.routerBFCache
    ),
    'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
      config.experimental.optimisticClientCache ?? true,
    'process.env.__NEXT_MIDDLEWARE_PREFETCH':
      config.experimental.middlewarePrefetch ?? 'flexible',
    'process.env.__NEXT_CROSS_ORIGIN': config.crossOrigin,
    'process.browser': isClient,
    '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)
      ? {
          'process.env.__NEXT_DIST_DIR': distDir,
        }
      : {}),
    // This is used in devtools to strip the project path in edge runtime,
    // as there's only a dummy `dir` value (`.`) as edge runtime doesn't have concept of file system.
    ...(dev && isEdgeServer
      ? {
          'process.env.__NEXT_EDGE_PROJECT_DIR': isTurbopack
            ? path.relative(process.cwd(), projectPath)
            : projectPath,
        }
      : {}),
    'process.env.__NEXT_BASE_PATH': config.basePath,
    'process.env.__NEXT_CASE_SENSITIVE_ROUTES': Boolean(
      config.experimental.caseSensitiveRoutes
    ),
    'process.env.__NEXT_REWRITES': rewrites as any,
    'process.env.__NEXT_TRAILING_SLASH': config.trailingSlash,
    'process.env.__NEXT_DEV_INDICATOR': config.devIndicators !== false,
    'process.env.__NEXT_DEV_INDICATOR_POSITION':
      config.devIndicators === false
        ? 'bottom-left' // This will not be used as the indicator is disabled.
        : config.devIndicators.position ?? 'bottom-left',
    '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_CSS':
      (config.experimental.optimizeCss && !dev) ?? false,
    'process.env.__NEXT_SCRIPT_WORKERS':
      (config.experimental.nextScriptWorkers && !dev) ?? false,
    'process.env.__NEXT_SCROLL_RESTORATION':
      config.experimental.scrollRestoration ?? false,
    ...getImageConfig(config, dev),
    'process.env.__NEXT_ROUTER_BASEPATH': config.basePath,
    '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 ?? false,
    'process.env.__NEXT_I18N_CONFIG': config.i18n || '',
    'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':
      config.skipMiddlewareUrlNormalize,
    'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':
      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) ??
      false,
    'process.env.__NEXT_WEB_VITALS_ATTRIBUTION':
      config.experimental.webVitalsAttribution ?? false,
    'process.env.__NEXT_LINK_NO_TOUCH_START':
      config.experimental.linkNoTouchStart ?? false,
    'process.env.__NEXT_ASSET_PREFIX': config.assetPrefix,
    'process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS':
      !!config.experimental.authInterrupts,
    'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(
      process.env.NEXT_TELEMETRY_DISABLED
    ),
    ...(isNodeServer || isEdgeServer
      ? {
          // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
          // This is typically found in unmaintained modules from the
          // pre-webpack era (common in server-side code)
          'global.GENTLY': false,
        }
      : undefined),
    ...(isNodeServer || isEdgeServer
      ? {
          'process.env.__NEXT_EXPERIMENTAL_REACT':
            needsExperimentalReact(config),
        }
      : undefined),

    'process.env.__NEXT_MULTI_ZONE_DRAFT_MODE':
      config.experimental.multiZoneDraftMode ?? false,
    'process.env.__NEXT_TRUST_HOST_HEADER':
      config.experimental.trustHostHeader ?? false,
    'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS':
      config.experimental.allowedRevalidateHeaderKeys ?? [],
    ...(isNodeServer
      ? {
          'process.env.__NEXT_RELATIVE_DIST_DIR': config.distDir,
          'process.env.__NEXT_RELATIVE_PROJECT_DIR': path.relative(
            process.cwd(),
            projectPath
          ),
        }
      : {}),
    'process.env.__NEXT_DEVTOOL_SEGMENT_EXPLORER':
      !!config.experimental.devtoolSegmentExplorer,

    'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(
      config.experimental.browserDebugInfoInTerminal || false
    ),

    // The devtools need to know whether or not to show an option to clear the
    // bundler cache. This option may be removed later once Turbopack's
    // persistent cache feature is more stable.
    //
    // This environment value is currently best-effort:
    // - It's possible to disable the webpack filesystem cache, but it's
    //   unlikely for a user to do that.
    // - Rspack's persistent cache is unstable and requires a different
    //   configuration than webpack to enable (which we don't do).
    //
    // In the worst case we'll show an option to clear the cache, but it'll be a
    // no-op that just restarts the development server.
    'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':
      !isTurbopack || (config.experimental.turbopackPersistentCaching ?? false),
    'process.env.__NEXT_OPTIMIZE_ROUTER_SCROLL':
      config.experimental.optimizeRouterScrolling ?? false,
  }

  const userDefines = config.compiler?.define ?? {}
  for (const key in userDefines) {
    if (defineEnv.hasOwnProperty(key)) {
      throw new Error(
        `The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`
      )
    }
    defineEnv[key] = userDefines[key]
  }

  if (isNodeServer || isEdgeServer) {
    const userDefinesServer = config.compiler?.defineServer ?? {}
    for (const key in userDefinesServer) {
      if (defineEnv.hasOwnProperty(key)) {
        throw new Error(
          `The \`compiler.defineServer\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`
        )
      }
      defineEnv[key] = userDefinesServer[key]
    }
  }

  const serializedDefineEnv = serializeDefineEnv(defineEnv)

  // we delay inlining these values until after the build
  // with flying shuttle enabled so we can update them
  // without invalidating entries
  if (!dev && omitNonDeterministic) {
    // client uses window. instead of leaving process.env
    // in case process isn't polyfilled on client already
    // since by this point it won't be added by webpack
    const safeKey = (key: string) =>
      isClient ? `window.${key.split('.').pop()}` : key

    for (const key in nextPublicEnv) {
      serializedDefineEnv[key] = safeKey(key)
    }
    for (const key in nextConfigEnv) {
      serializedDefineEnv[key] = safeKey(key)
    }
    for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {
      serializedDefineEnv[key] = safeKey(key)
    }
  }

  return serializedDefineEnv
}