Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
1309deea
Unverified
Commit
1309deea
authored
Jul 10, 2024
by
Jiwon Choi
Committed by
GitHub
Jul 10, 2024
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
feat: type hint for `env` in dev mode (#67157)
parent
caa2bb1d
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
225 additions
and
9 deletions
+225
-9
index.ts
packages/next-env/index.ts
+7
-5
config-schema.ts
packages/next/src/server/config-schema.ts
+1
-0
config-shared.ts
packages/next/src/server/config-shared.ts
+8
-0
create-env-definitions.test.ts
...rc/server/lib/experimental/create-env-definitions.test.ts
+48
-0
create-env-definitions.ts
...ext/src/server/lib/experimental/create-env-definitions.ts
+38
-0
setup-dev-bundler.ts
...ges/next/src/server/lib/router-utils/setup-dev-bundler.ts
+28
-4
.env
test/development/app-dir/typed-env/.env
+1
-0
.env.development.local
test/development/app-dir/typed-env/.env.development.local
+1
-0
.env.local
test/development/app-dir/typed-env/.env.local
+1
-0
.env.production.local
test/development/app-dir/typed-env/.env.production.local
+1
-0
layout.tsx
test/development/app-dir/typed-env/app/layout.tsx
+8
-0
page.tsx
test/development/app-dir/typed-env/app/page.tsx
+3
-0
next.config.js
test/development/app-dir/typed-env/next.config.js
+13
-0
typed-env.test.ts
test/development/app-dir/typed-env/typed-env.test.ts
+67
-0
No files found.
packages/next-env/index.ts
View file @
1309deea
...
@@ -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
}
}
}
packages/next/src/server/config-schema.ts
View file @
1309deea
...
@@ -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
...
...
packages/next/src/server/config-shared.ts
View file @
1309deea
...
@@ -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
,
...
...
packages/next/src/server/lib/experimental/create-env-definitions.test.ts
0 → 100644
View file @
1309deea
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 {}"
`
)
})
})
packages/next/src/server/lib/experimental/create-env-definitions.ts
0 → 100644
View file @
1309deea
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
)
}
}
packages/next/src/server/lib/router-utils/setup-dev-bundler.ts
View file @
1309deea
...
@@ -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
},
])
])
...
...
test/development/app-dir/typed-env/.env
0 → 100644
View file @
1309deea
FROM_ENV="FROM_ENV"
\ No newline at end of file
test/development/app-dir/typed-env/.env.development.local
0 → 100644
View file @
1309deea
FROM_DEV_ENV_LOCAL="FROM_DEV_ENV_LOCAL"
\ No newline at end of file
test/development/app-dir/typed-env/.env.local
0 → 100644
View file @
1309deea
FROM_ENV_LOCAL="FROM_ENV_LOCAL"
\ No newline at end of file
test/development/app-dir/typed-env/.env.production.local
0 → 100644
View file @
1309deea
FROM_PROD_ENV_LOCAL="FROM_PROD_ENV_LOCAL"
\ No newline at end of file
test/development/app-dir/typed-env/app/layout.tsx
0 → 100644
View file @
1309deea
import
{
ReactNode
}
from
'react'
export
default
function
Root
({
children
}:
{
children
:
ReactNode
})
{
return
(
<
html
>
<
body
>
{
children
}
</
body
>
</
html
>
)
}
test/development/app-dir/typed-env/app/page.tsx
0 → 100644
View file @
1309deea
export
default
function
Page
()
{
return
<
p
>
hello world
</
p
>
}
test/development/app-dir/typed-env/next.config.js
0 → 100644
View file @
1309deea
/**
* @type {import('next').NextConfig}
*/
const
nextConfig
=
{
env
:
{
FROM_NEXT_CONFIG
:
'FROM_NEXT_CONFIG'
,
},
experimental
:
{
typedEnv
:
true
,
},
}
module
.
exports
=
nextConfig
test/development/app-dir/typed-env/typed-env.test.ts
0 → 100644
View file @
1309deea
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
})
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment