Unverified Commit 73f547a6 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Display where the env was loaded from when enabled `typedEnv` (#70951)

### Why?

This PR added an indication of where the env was loaded from when
`experimental.typedEnv` was enabled. Also, it allows the user to set
`NODE_ENV=production` to enable the `typedEnv` feature for
`.env.production*` files.

![CleanShot 2024-11-21 at 19 48
20](https://github.com/user-attachments/assets/ce3c7180-f26a-4378-a74f-a5998a363211)

### How?

Modified `@next/env` to pass parsed envs along with the `loadedEnvFiles`
value and used the location to indicate via JSDoc.
parent 7885f884
...@@ -160,7 +160,7 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) { ...@@ -160,7 +160,7 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) {
> >
> When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links. > When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links.
### With Async Server Componens ### With Async Server Components
To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher. To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
......
...@@ -8,6 +8,7 @@ export type Env = { [key: string]: string | undefined } ...@@ -8,6 +8,7 @@ export type Env = { [key: string]: string | undefined }
export type LoadedEnvFiles = Array<{ export type LoadedEnvFiles = Array<{
path: string path: string
contents: string contents: string
env: Env
}> }>
export let initialEnv: Env | undefined = undefined export let initialEnv: Env | undefined = undefined
...@@ -91,6 +92,9 @@ export function processEnv( ...@@ -91,6 +92,9 @@ export function processEnv(
parsed[key] = result.parsed?.[key]! parsed[key] = result.parsed?.[key]!
} }
} }
// Add the parsed env to the loadedEnvFiles
envFile.env = result.parsed || {}
} catch (err) { } catch (err) {
log.error( log.error(
`Failed to load env from ${path.join(dir || '', envFile.path)}`, `Failed to load env from ${path.join(dir || '', envFile.path)}`,
...@@ -157,6 +161,7 @@ export function loadEnvConfig( ...@@ -157,6 +161,7 @@ export function loadEnvConfig(
cachedLoadedEnvFiles.push({ cachedLoadedEnvFiles.push({
path: envFile, path: envFile,
contents, contents,
env: {}, // This will be populated in processEnv
}) })
} catch (err: any) { } catch (err: any) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
......
...@@ -2,24 +2,43 @@ import { createEnvDefinitions } from './create-env-definitions' ...@@ -2,24 +2,43 @@ import { createEnvDefinitions } from './create-env-definitions'
describe('create-env-definitions', () => { describe('create-env-definitions', () => {
it('should create env definitions', async () => { it('should create env definitions', async () => {
const env = { const loadedEnvFiles = [
FROM_DEV_ENV_LOCAL: 'FROM_DEV_ENV_LOCAL', {
FROM_ENV_LOCAL: 'FROM_ENV_LOCAL', path: '.env.local',
FROM_ENV: 'FROM_ENV', contents: '',
FROM_NEXT_CONFIG: 'FROM_NEXT_CONFIG', env: {
} FROM_ENV_LOCAL: 'FROM_ENV_LOCAL',
},
},
{
path: '.env.development.local',
contents: '',
env: {
FROM_ENV_DEV_LOCAL: 'FROM_ENV_DEV_LOCAL',
},
},
{
path: 'next.config.js',
contents: '',
env: {
FROM_NEXT_CONFIG: 'FROM_NEXT_CONFIG',
},
},
]
const definitionStr = await createEnvDefinitions({ const definitionStr = await createEnvDefinitions({
distDir: '/dist', distDir: '/dist',
env, loadedEnvFiles,
}) })
expect(definitionStr).toMatchInlineSnapshot(` expect(definitionStr).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables "// Type definitions for Next.js environment variables
declare global { declare global {
namespace NodeJS { namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
FROM_DEV_ENV_LOCAL?: string /** Loaded from \`.env.local\` */
FROM_ENV_LOCAL?: string FROM_ENV_LOCAL?: string
FROM_ENV?: string /** Loaded from \`.env.development.local\` */
FROM_ENV_DEV_LOCAL?: string
/** Loaded from \`next.config.js\` */
FROM_NEXT_CONFIG?: string FROM_NEXT_CONFIG?: string
} }
} }
...@@ -31,7 +50,7 @@ describe('create-env-definitions', () => { ...@@ -31,7 +50,7 @@ describe('create-env-definitions', () => {
it('should allow empty env', async () => { it('should allow empty env', async () => {
const definitionStr = await createEnvDefinitions({ const definitionStr = await createEnvDefinitions({
distDir: '/dist', distDir: '/dist',
env: {}, loadedEnvFiles: [],
}) })
expect(definitionStr).toMatchInlineSnapshot(` expect(definitionStr).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables "// Type definitions for Next.js environment variables
...@@ -45,4 +64,46 @@ describe('create-env-definitions', () => { ...@@ -45,4 +64,46 @@ describe('create-env-definitions', () => {
export {}" export {}"
`) `)
}) })
it('should dedupe env definitions in order of priority', async () => {
const loadedEnvFiles = [
{
path: '.env.local',
contents: '',
env: {
DUPLICATE_ENV: 'DUPLICATE_ENV',
},
},
{
path: '.env.development.local',
contents: '',
env: {
DUPLICATE_ENV: 'DUPLICATE_ENV',
},
},
{
path: 'next.config.js',
contents: '',
env: {
DUPLICATE_ENV: 'DUPLICATE_ENV',
},
},
]
const definitionStr = await createEnvDefinitions({
distDir: '/dist',
loadedEnvFiles,
})
expect(definitionStr).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
/** Loaded from \`.env.local\` */
DUPLICATE_ENV?: string
}
}
}
export {}"
`)
})
}) })
import type { Env } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import { join } from 'node:path' import { join } from 'node:path'
import { writeFile } from 'node:fs/promises' import { writeFile } from 'node:fs/promises'
export async function createEnvDefinitions({ export async function createEnvDefinitions({
distDir, distDir,
env, loadedEnvFiles,
}: { }: {
distDir: string distDir: string
env: Env loadedEnvFiles: LoadedEnvFiles
}) { }) {
const envKeysStr = Object.keys(env) const envLines = []
.map((key) => ` ${key}?: string`) const seenKeys = new Set()
.join('\n') // env files are in order of priority
for (const { path, env } of loadedEnvFiles) {
for (const key in env) {
if (!seenKeys.has(key)) {
envLines.push(` /** Loaded from \`${path}\` */`)
envLines.push(` ${key}?: string`)
seenKeys.add(key)
}
}
}
const envStr = envLines.join('\n')
const definitionStr = `// Type definitions for Next.js environment variables const definitionStr = `// Type definitions for Next.js environment variables
declare global { declare global {
namespace NodeJS { namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
${envKeysStr} ${envStr}
} }
} }
} }
......
...@@ -583,9 +583,9 @@ async function startWatcher(opts: SetupOpts) { ...@@ -583,9 +583,9 @@ async function startWatcher(opts: SetupOpts) {
if (envChange || tsconfigChange) { if (envChange || tsconfigChange) {
if (envChange) { if (envChange) {
const { parsedEnv } = loadEnvConfig( const { loadedEnvFiles } = loadEnvConfig(
dir, dir,
true, process.env.NODE_ENV === 'development',
Log, Log,
true, true,
(envFilePath) => { (envFilePath) => {
...@@ -597,7 +597,14 @@ async function startWatcher(opts: SetupOpts) { ...@@ -597,7 +597,14 @@ async function startWatcher(opts: SetupOpts) {
// do not await, this is not essential for further process // do not await, this is not essential for further process
createEnvDefinitions({ createEnvDefinitions({
distDir, distDir,
env: { ...parsedEnv, ...nextConfig.env }, loadedEnvFiles: [
...loadedEnvFiles,
{
path: nextConfig.configFileName,
env: nextConfig.env,
contents: '',
},
],
}) })
} }
......
FROM_ENV_DEV="FROM_ENV_DEV"
\ No newline at end of file
FROM_DEV_ENV_LOCAL="FROM_DEV_ENV_LOCAL" FROM_ENV_DEV_LOCAL="FROM_ENV_DEV_LOCAL"
\ No newline at end of file \ No newline at end of file
FROM_PROD_ENV_LOCAL="FROM_PROD_ENV_LOCAL" FROM_ENV_PROD_LOCAL="FROM_ENV_PROD_LOCAL"
\ No newline at end of file
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('typed-env', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
NODE_ENV: 'production',
},
})
it('should have env types from next config', async () => {
await retry(async () => {
const envDTS = await next.readFile('.next/types/env.d.ts')
// since NODE_ENV is production, env types will
// not include development-specific env
expect(envDTS).not.toContain('FROM_ENV_DEV')
expect(envDTS).not.toContain('FROM_ENV_DEV_LOCAL')
expect(envDTS).toMatchInlineSnapshot(`
"// Type definitions for Next.js environment variables
declare global {
namespace NodeJS {
interface ProcessEnv {
/** Loaded from \`.env.production.local\` */
FROM_ENV_PROD_LOCAL?: string
/** Loaded from \`.env.local\` */
FROM_ENV_LOCAL?: string
/** Loaded from \`.env.production\` */
FROM_ENV_PROD?: string
/** Loaded from \`.env\` */
FROM_ENV?: string
/** Loaded from \`next.config.js\` */
FROM_NEXT_CONFIG?: string
}
}
}
export {}"
`)
})
})
// TODO: test for deleting .env & updating env.d.ts
})
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
describe('typed-env', () => { describe('typed-env', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -7,36 +7,41 @@ describe('typed-env', () => { ...@@ -7,36 +7,41 @@ describe('typed-env', () => {
}) })
it('should have env types from next config', async () => { it('should have env types from next config', async () => {
await check( await retry(async () => {
async () => { const envDTS = await next.readFile('.next/types/env.d.ts')
return await next.readFile('.next/types/env.d.ts') // since NODE_ENV is development, env types will
}, // not include production-specific env
expect(envDTS).not.toContain('FROM_ENV_PROD')
expect(envDTS).not.toContain('FROM_ENV_PROD_LOCAL')
// should not include from production-specific env expect(envDTS).toMatchInlineSnapshot(`
// e.g. FROM_PROD_ENV_LOCAL?: string "// Type definitions for Next.js environment variables
`// Type definitions for Next.js environment variables declare global {
declare global { namespace NodeJS {
namespace NodeJS { interface ProcessEnv {
interface ProcessEnv { /** Loaded from \`.env.development.local\` */
FROM_DEV_ENV_LOCAL?: string FROM_ENV_DEV_LOCAL?: string
FROM_ENV_LOCAL?: string /** Loaded from \`.env.local\` */
FROM_ENV?: string FROM_ENV_LOCAL?: string
FROM_NEXT_CONFIG?: string /** Loaded from \`.env.development\` */
} FROM_ENV_DEV?: string
} /** Loaded from \`.env\` */
} FROM_ENV?: string
export {}` /** Loaded from \`next.config.js\` */
) FROM_NEXT_CONFIG?: string
}
}
}
export {}"
`)
})
}) })
it('should rewrite env types if .env is modified', async () => { it('should rewrite env types if .env is modified', async () => {
await check( await retry(async () => {
async () => { const content = await next.readFile('.next/types/env.d.ts')
return await next.readFile('.next/types/env.d.ts') expect(content).toContain('FROM_ENV')
}, })
// env.d.ts is written from original .env
/FROM_ENV/
)
// modify .env // modify .env
await next.patchFile('.env', 'MODIFIED_ENV="MODIFIED_ENV"') await next.patchFile('.env', 'MODIFIED_ENV="MODIFIED_ENV"')
...@@ -44,23 +49,29 @@ export {}` ...@@ -44,23 +49,29 @@ export {}`
// should not include from original .env // should not include from original .env
// e.g. FROM_ENV?: string // e.g. FROM_ENV?: string
// but have MODIFIED_ENV?: string // but have MODIFIED_ENV?: string
await check( await retry(async () => {
async () => { const content = await next.readFile('.next/types/env.d.ts')
return await next.readFile('.next/types/env.d.ts') expect(content).toMatchInlineSnapshot(`
}, "// Type definitions for Next.js environment variables
`// Type definitions for Next.js environment variables declare global {
declare global { namespace NodeJS {
namespace NodeJS { interface ProcessEnv {
interface ProcessEnv { /** Loaded from \`.env.development.local\` */
FROM_DEV_ENV_LOCAL?: string FROM_ENV_DEV_LOCAL?: string
FROM_ENV_LOCAL?: string /** Loaded from \`.env.local\` */
MODIFIED_ENV?: string FROM_ENV_LOCAL?: string
FROM_NEXT_CONFIG?: string /** Loaded from \`.env.development\` */
} FROM_ENV_DEV?: string
} /** Loaded from \`.env\` */
} FROM_ENV?: string
export {}` /** Loaded from \`next.config.js\` */
) FROM_NEXT_CONFIG?: string
}
}
}
export {}"
`)
})
}) })
// TODO: test for deleting .env & updating env.d.ts // 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