Unverified Commit 1309deea authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

feat: type hint for `env` in dev mode (#67157)

parent caa2bb1d
...@@ -12,6 +12,7 @@ export type LoadedEnvFiles = Array<{ ...@@ -12,6 +12,7 @@ export type LoadedEnvFiles = Array<{
export let initialEnv: Env | undefined = undefined export let initialEnv: Env | undefined = undefined
let combinedEnv: Env | undefined = undefined let combinedEnv: Env | undefined = undefined
let parsedEnv: Env | undefined = undefined
let cachedLoadedEnvFiles: LoadedEnvFiles = [] let cachedLoadedEnvFiles: LoadedEnvFiles = []
let previousLoadedEnvFiles: LoadedEnvFiles = [] let previousLoadedEnvFiles: LoadedEnvFiles = []
...@@ -55,7 +56,7 @@ export function processEnv( ...@@ -55,7 +56,7 @@ export function processEnv(
!forceReload && !forceReload &&
(process.env.__NEXT_PROCESSED_ENV || loadedEnvFiles.length === 0) (process.env.__NEXT_PROCESSED_ENV || loadedEnvFiles.length === 0)
) { ) {
return process.env as Env return [process.env as Env]
} }
// flag that we processed the environment values already. // flag that we processed the environment values already.
process.env.__NEXT_PROCESSED_ENV = 'true' process.env.__NEXT_PROCESSED_ENV = 'true'
...@@ -97,7 +98,7 @@ export function processEnv( ...@@ -97,7 +98,7 @@ export function processEnv(
) )
} }
} }
return Object.assign(process.env, parsed) return [Object.assign(process.env, parsed), parsed]
} }
export function resetEnv() { export function resetEnv() {
...@@ -114,6 +115,7 @@ export function loadEnvConfig( ...@@ -114,6 +115,7 @@ export function loadEnvConfig(
onReload?: (envFilePath: string) => void onReload?: (envFilePath: string) => void
): { ): {
combinedEnv: Env combinedEnv: Env
parsedEnv: Env | undefined
loadedEnvFiles: LoadedEnvFiles loadedEnvFiles: LoadedEnvFiles
} { } {
if (!initialEnv) { if (!initialEnv) {
...@@ -121,7 +123,7 @@ export function loadEnvConfig( ...@@ -121,7 +123,7 @@ export function loadEnvConfig(
} }
// only reload env when forceReload is specified // only reload env when forceReload is specified
if (combinedEnv && !forceReload) { if (combinedEnv && !forceReload) {
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles } return { combinedEnv, parsedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
} }
replaceProcessEnv(initialEnv) replaceProcessEnv(initialEnv)
previousLoadedEnvFiles = cachedLoadedEnvFiles previousLoadedEnvFiles = cachedLoadedEnvFiles
...@@ -162,12 +164,12 @@ export function loadEnvConfig( ...@@ -162,12 +164,12 @@ export function loadEnvConfig(
} }
} }
} }
combinedEnv = processEnv( ;[combinedEnv, parsedEnv] = processEnv(
cachedLoadedEnvFiles, cachedLoadedEnvFiles,
dir, dir,
log, log,
forceReload, forceReload,
onReload onReload
) )
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles } return { combinedEnv, parsedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
} }
...@@ -436,6 +436,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -436,6 +436,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
]), ]),
staticGenerationRetryCount: z.number().int().optional(), staticGenerationRetryCount: z.number().int().optional(),
typedEnv: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -339,6 +339,13 @@ export interface ExperimentalConfig { ...@@ -339,6 +339,13 @@ export interface ExperimentalConfig {
*/ */
typedRoutes?: boolean typedRoutes?: boolean
/**
* Enable type-checking and autocompletion for environment variables.
*
* @default false
*/
typedEnv?: boolean
/** /**
* Runs the compilations for server and edge in parallel instead of in serial. * Runs the compilations for server and edge in parallel instead of in serial.
* This will make builds faster if there is enough server and edge functions * This will make builds faster if there is enough server and edge functions
...@@ -966,6 +973,7 @@ export const defaultConfig: NextConfig = { ...@@ -966,6 +973,7 @@ export const defaultConfig: NextConfig = {
turbo: undefined, turbo: undefined,
turbotrace: undefined, turbotrace: undefined,
typedRoutes: false, typedRoutes: false,
typedEnv: false,
instrumentationHook: false, instrumentationHook: false,
clientTraceMetadata: undefined, clientTraceMetadata: undefined,
parallelServerCompiles: false, parallelServerCompiles: false,
......
import { createEnvDefinitions } from './create-env-definitions'
describe('create-env-definitions', () => {
it('should create env definitions', async () => {
const env = {
FROM_DEV_ENV_LOCAL: 'FROM_DEV_ENV_LOCAL',
FROM_ENV_LOCAL: 'FROM_ENV_LOCAL',
FROM_ENV: 'FROM_ENV',
FROM_NEXT_CONFIG: 'FROM_NEXT_CONFIG',
}
const definitionStr = await createEnvDefinitions({
distDir: '/dist',
env,
})
expect(definitionStr).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
FROM_DEV_ENV_LOCAL: readonly string
FROM_ENV_LOCAL: readonly string
FROM_ENV: readonly string
FROM_NEXT_CONFIG: readonly string
}
}
}
export {}"
`)
})
it('should allow empty env', async () => {
const definitionStr = await createEnvDefinitions({
distDir: '/dist',
env: {},
})
expect(definitionStr).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
}
}
}
export {}"
`)
})
})
import type { Env } from '@next/env'
import { join } from 'node:path'
import { writeFile } from 'node:fs/promises'
export async function createEnvDefinitions({
distDir,
env,
}: {
distDir: string
env: Env
}) {
const envKeysStr = Object.keys(env)
.map((key) => ` ${key}: readonly string`)
.join('\n')
const definitionStr = `// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
${envKeysStr}
}
}
}
export {}`
if (process.env.NODE_ENV === 'test') {
return definitionStr
}
try {
// we expect the types directory to already exist
const envDtsPath = join(distDir, 'types', 'env.d.ts')
// do not await, this is not essential for further process
writeFile(envDtsPath, definitionStr, 'utf-8')
} catch (e) {
console.error('Failed to write env.d.ts:', e)
}
}
...@@ -11,6 +11,7 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types' ...@@ -11,6 +11,7 @@ import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
import { createDefineEnv, type Project } from '../../../build/swc' import { createDefineEnv, type Project } from '../../../build/swc'
import fs from 'fs' import fs from 'fs'
import { mkdir } from 'fs/promises'
import url from 'url' import url from 'url'
import path from 'path' import path from 'path'
import qs from 'querystring' import qs from 'querystring'
...@@ -82,6 +83,7 @@ import { generateEncryptionKeyBase64 } from '../../app-render/encryption-utils' ...@@ -82,6 +83,7 @@ import { generateEncryptionKeyBase64 } from '../../app-render/encryption-utils'
import { ModuleBuildError } from '../../dev/turbopack-utils' import { ModuleBuildError } from '../../dev/turbopack-utils'
import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route' import { isMetadataRoute } from '../../../lib/metadata/is-metadata-route'
import { normalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route' import { normalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route'
import { createEnvDefinitions } from '../experimental/create-env-definitions'
export type SetupOpts = { export type SetupOpts = {
renderServer: LazyRenderServerInstance renderServer: LazyRenderServerInstance
...@@ -150,6 +152,14 @@ async function startWatcher(opts: SetupOpts) { ...@@ -150,6 +152,14 @@ async function startWatcher(opts: SetupOpts) {
const distDir = path.join(opts.dir, opts.nextConfig.distDir) const distDir = path.join(opts.dir, opts.nextConfig.distDir)
// we ensure the types directory exists here
if (usingTypeScript) {
const distTypesDir = path.join(distDir, 'types')
if (!fs.existsSync(distTypesDir)) {
await mkdir(distTypesDir, { recursive: true })
}
}
setGlobal('distDir', distDir) setGlobal('distDir', distDir)
setGlobal('phase', PHASE_DEVELOPMENT_SERVER) setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
...@@ -546,10 +556,24 @@ async function startWatcher(opts: SetupOpts) { ...@@ -546,10 +556,24 @@ async function startWatcher(opts: SetupOpts) {
if (envChange || tsconfigChange) { if (envChange || tsconfigChange) {
if (envChange) { if (envChange) {
// only log changes in router server const { parsedEnv } = loadEnvConfig(
loadEnvConfig(dir, true, Log, true, (envFilePath) => { dir,
Log.info(`Reload env: ${envFilePath}`) true,
}) Log,
true,
(envFilePath) => {
Log.info(`Reload env: ${envFilePath}`)
}
)
if (usingTypeScript && nextConfig.experimental?.typedEnv) {
// do not await, this is not essential for further process
createEnvDefinitions({
distDir,
env: { ...parsedEnv, ...nextConfig.env },
})
}
await propagateServerField(opts, 'loadEnvConfig', [ await propagateServerField(opts, 'loadEnvConfig', [
{ dev: true, forceReload: true, silent: true }, { dev: true, forceReload: true, silent: true },
]) ])
......
FROM_ENV="FROM_ENV"
\ No newline at end of file
FROM_DEV_ENV_LOCAL="FROM_DEV_ENV_LOCAL"
\ No newline at end of file
FROM_ENV_LOCAL="FROM_ENV_LOCAL"
\ No newline at end of file
FROM_PROD_ENV_LOCAL="FROM_PROD_ENV_LOCAL"
\ No newline at end of file
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
env: {
FROM_NEXT_CONFIG: 'FROM_NEXT_CONFIG',
},
experimental: {
typedEnv: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('typed-env', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should have env types from next config', async () => {
await check(
async () => {
return await next.readFile('.next/types/env.d.ts')
},
// should not include from production-specific env
// e.g. FROM_PROD_ENV_LOCAL: readonly string
`// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
FROM_DEV_ENV_LOCAL: readonly string
FROM_ENV_LOCAL: readonly string
FROM_ENV: readonly string
FROM_NEXT_CONFIG: readonly string
}
}
}
export {}`
)
})
it('should rewrite env types if .env is modified', async () => {
await check(
async () => {
return await next.readFile('.next/types/env.d.ts')
},
// env.d.ts is written from original .env
/FROM_ENV: readonly string/
)
// modify .env
await next.patchFile('.env', 'MODIFIED_ENV="MODIFIED_ENV"')
// should not include from original .env
// e.g. FROM_ENV: readonly string
// but have MODIFIED_ENV: readonly string
await check(
async () => {
return await next.readFile('.next/types/env.d.ts')
},
`// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
FROM_DEV_ENV_LOCAL: readonly string
FROM_ENV_LOCAL: readonly string
MODIFIED_ENV: readonly string
FROM_NEXT_CONFIG: readonly string
}
}
}
export {}`
)
})
// TODO: test for deleting .env & updating env.d.ts
})
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