@@ -2,6 +2,8 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
3
3
import type { CloudflareContext } from "../../api" ;
4
4
// @ts -expect-error: resolved by wrangler build
5
+ import * as nextEnvVars from "./env/next-env.mjs" ;
6
+ // @ts -expect-error: resolved by wrangler build
5
7
import { handler as middlewareHandler } from "./middleware/handler.mjs" ;
6
8
// @ts -expect-error: resolved by wrangler build
7
9
import { handler as serverHandler } from "./server-functions/default/handler.mjs" ;
@@ -21,15 +23,15 @@ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
21
23
}
22
24
) ;
23
25
26
+ // Populate process.env on the first request
27
+ let processEnvPopulated = false ;
28
+
24
29
export default {
25
30
async fetch ( request , env , ctx ) {
26
31
return cloudflareContextALS . run ( { env, ctx, cf : request . cf } , async ( ) => {
27
32
const url = new URL ( request . url ) ;
28
33
29
- if ( process . env . __PROCESS_ENV_POPULATED !== "1" ) {
30
- await populateProcessEnv ( url , env . NEXTJS_ENV ) ;
31
- process . env . __PROCESS_ENV_POPULATED = "1" ;
32
- }
34
+ populateProcessEnv ( url , env . NEXTJS_ENV ) ;
33
35
34
36
if ( url . pathname === "/_next/image" ) {
35
37
const imageUrl = url . searchParams . get ( "url" ) ?? "" ;
@@ -59,10 +61,11 @@ export default {
59
61
*
60
62
* Note that cloudflare env string values are copied by the middleware handler.
61
63
*/
62
- async function populateProcessEnv ( url : URL , nextJsEnv ?: string ) {
63
- // @ts -expect-error: resolved by wrangler build
64
- const nextEnvVars = await import ( "./.env.mjs" ) ;
65
-
64
+ function populateProcessEnv ( url : URL , nextJsEnv ?: string ) {
65
+ if ( processEnvPopulated ) {
66
+ return ;
67
+ }
68
+ processEnvPopulated = true ;
66
69
const mode = nextJsEnv ?? "production" ;
67
70
68
71
if ( nextEnvVars [ mode ] ) {
0 commit comments