Unverified Commit d0dfc63c authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Move static-env imports (#77035)

In https://github.com/vercel/next.js/pull/76990 we noticed that imports
in `base-server`/`next-server` are being processed by turbopack which
needs to be investigated further although for now this moves the imports
to only import the necessary files in `next-server` to avoid bundling
time regression.
parent eac3f2ec
...@@ -207,7 +207,8 @@ import { ...@@ -207,7 +207,8 @@ import {
import { turbopackBuild } from './turbopack-build' import { turbopackBuild } from './turbopack-build'
import { isPersistentCachingEnabled } from '../shared/lib/turbopack/utils' import { isPersistentCachingEnabled } from '../shared/lib/turbopack/utils'
import { inlineStaticEnv, populateStaticEnv } from '../lib/inline-static-env' import { inlineStaticEnv } from '../lib/inline-static-env'
import { populateStaticEnv } from '../lib/static-env'
type Fallback = null | boolean | string type Fallback = null | boolean | string
......
...@@ -6,17 +6,10 @@ import type { MiddlewareMatcher } from '../../analysis/get-page-static-info' ...@@ -6,17 +6,10 @@ import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { needsExperimentalReact } from '../../../lib/needs-experimental-react' import { needsExperimentalReact } from '../../../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../../../server/lib/experimental/ppr' import { checkIsAppPPREnabled } from '../../../server/lib/experimental/ppr'
import {
function errorIfEnvConflicted(config: NextConfigComplete, key: string) { getNextConfigEnv,
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key) getNextPublicEnvironmentVariables,
const hasNextRuntimeKey = key === 'NEXT_RUNTIME' } from '../../../lib/static-env'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
}
type BloomFilter = ReturnType< type BloomFilter = ReturnType<
import('../../../shared/lib/bloom-filter').BloomFilter['export'] import('../../../shared/lib/bloom-filter').BloomFilter['export']
...@@ -56,39 +49,6 @@ interface SerializedDefineEnv { ...@@ -56,39 +49,6 @@ interface SerializedDefineEnv {
[key: string]: string [key: string]: string
} }
/**
* Collects all environment variables that are using the `NEXT_PUBLIC_` prefix.
*/
export function getNextPublicEnvironmentVariables(): DefineEnv {
const defineEnv: DefineEnv = {}
for (const key in process.env) {
if (key.startsWith('NEXT_PUBLIC_')) {
const value = process.env[key]
if (value != null) {
defineEnv[`process.env.${key}`] = value
}
}
}
return defineEnv
}
/**
* Collects the `env` config value from the Next.js config.
*/
export function getNextConfigEnv(config: NextConfigComplete): DefineEnv {
// Refactored code below to use for-of
const defineEnv: DefineEnv = {}
const env = config.env
for (const key in env) {
const value = env[key]
if (value != null) {
errorIfEnvConflicted(config, key)
defineEnv[`process.env.${key}`] = value
}
}
return defineEnv
}
/** /**
* Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value. * Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.
*/ */
......
...@@ -3,38 +3,13 @@ import path from 'path' ...@@ -3,38 +3,13 @@ import path from 'path'
import crypto from 'crypto' import crypto from 'crypto'
import { promisify } from 'util' import { promisify } from 'util'
import globOriginal from 'next/dist/compiled/glob' import globOriginal from 'next/dist/compiled/glob'
import {
getNextConfigEnv,
getNextPublicEnvironmentVariables,
} from '../build/webpack/plugins/define-env-plugin'
import { Sema } from 'next/dist/compiled/async-sema' import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import { BUILD_MANIFEST } from '../shared/lib/constants' import { BUILD_MANIFEST } from '../shared/lib/constants'
import { getNextConfigEnv, getStaticEnv } from './static-env'
const glob = promisify(globOriginal) const glob = promisify(globOriginal)
const getStaticEnv = (config: NextConfigComplete) => {
const staticEnv: Record<string, string | undefined> = {
...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config),
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || '',
}
return staticEnv
}
export function populateStaticEnv(config: NextConfigComplete) {
// since inlining comes after static generation we need
// to ensure this value is assigned to process env so it
// can still be accessed
const staticEnv = getStaticEnv(config)
for (const key in staticEnv) {
const innerKey = key.split('.').pop() || ''
if (!process.env[innerKey]) {
process.env[innerKey] = staticEnv[key] || ''
}
}
}
export async function inlineStaticEnv({ export async function inlineStaticEnv({
distDir, distDir,
config, config,
......
import type { NextConfigComplete } from '../server/config-shared'
function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
const hasNextRuntimeKey = key === 'NEXT_RUNTIME'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
}
/**
* Collects all environment variables that are using the `NEXT_PUBLIC_` prefix.
*/
export function getNextPublicEnvironmentVariables() {
const defineEnv: Record<string, string | undefined> = {}
for (const key in process.env) {
if (key.startsWith('NEXT_PUBLIC_')) {
const value = process.env[key]
if (value != null) {
defineEnv[`process.env.${key}`] = value
}
}
}
return defineEnv
}
/**
* Collects the `env` config value from the Next.js config.
*/
export function getNextConfigEnv(config: NextConfigComplete) {
// Refactored code below to use for-of
const defineEnv: Record<string, string | undefined> = {}
const env = config.env
for (const key in env) {
const value = env[key]
if (value != null) {
errorIfEnvConflicted(config, key)
defineEnv[`process.env.${key}`] = value
}
}
return defineEnv
}
export function getStaticEnv(config: NextConfigComplete) {
const staticEnv: Record<string, string | undefined> = {
...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config),
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || '',
}
return staticEnv
}
export function populateStaticEnv(config: NextConfigComplete) {
// since inlining comes after static generation we need
// to ensure this value is assigned to process env so it
// can still be accessed
const staticEnv = getStaticEnv(config)
for (const key in staticEnv) {
const innerKey = key.split('.').pop() || ''
if (!process.env[innerKey]) {
process.env[innerKey] = staticEnv[key] || ''
}
}
}
...@@ -614,17 +614,6 @@ export default abstract class Server< ...@@ -614,17 +614,6 @@ export default abstract class Server<
reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,
} }
if (process.env.NEXT_RUNTIME !== 'edge') {
const { populateStaticEnv } =
require('../lib/inline-static-env') as typeof import('../lib/inline-static-env')
// when using compile mode static env isn't inlined so we
// need to populate in normal runtime env
if (this.renderOpts.isExperimentalCompile) {
populateStaticEnv(this.nextConfig)
}
}
// Initialize next/config with the environment configuration // Initialize next/config with the environment configuration
setConfig({ setConfig({
serverRuntimeConfig, serverRuntimeConfig,
......
...@@ -111,6 +111,7 @@ import { AwaiterOnce } from './after/awaiter' ...@@ -111,6 +111,7 @@ import { AwaiterOnce } from './after/awaiter'
import { AsyncCallbackSet } from './lib/async-callback-set' import { AsyncCallbackSet } from './lib/async-callback-set'
import { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers' import { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers'
import type { UnwrapPromise } from '../lib/coalesced-function' import type { UnwrapPromise } from '../lib/coalesced-function'
import { populateStaticEnv } from '../lib/static-env'
export * from './base-server' export * from './base-server'
...@@ -279,6 +280,12 @@ export default class NextNodeServer extends BaseServer< ...@@ -279,6 +280,12 @@ export default class NextNodeServer extends BaseServer<
console.error('Failed to prepare server', err) console.error('Failed to prepare server', err)
}) })
} }
// when using compile mode static env isn't inlined so we
// need to populate in normal runtime env
if (this.renderOpts.isExperimentalCompile) {
populateStaticEnv(this.nextConfig)
}
} }
public async unstable_preloadEntries(): Promise<void> { public async unstable_preloadEntries(): Promise<void> {
......
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