@@ -2,6 +2,8 @@ import { AsyncLocalStorage } from "node:async_hooks";
22
33import type { CloudflareContext } from "../../api" ;
44// @ts -expect-error: resolved by wrangler build
5+ import * as nextEnvVars from "./env/next-env.mjs" ;
6+ // @ts -expect-error: resolved by wrangler build
57import { handler as middlewareHandler } from "./middleware/handler.mjs" ;
68// @ts -expect-error: resolved by wrangler build
79import { handler as serverHandler } from "./server-functions/default/handler.mjs" ;
@@ -21,15 +23,15 @@ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
2123 }
2224) ;
2325
26+ // Populate process.env on the first request
27+ let processEnvPopulated = false ;
28+
2429export default {
2530 async fetch ( request , env , ctx ) {
2631 return cloudflareContextALS . run ( { env, ctx, cf : request . cf } , async ( ) => {
2732 const url = new URL ( request . url ) ;
2833
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 ) ;
3335
3436 if ( url . pathname === "/_next/image" ) {
3537 const imageUrl = url . searchParams . get ( "url" ) ?? "" ;
@@ -59,10 +61,11 @@ export default {
5961 *
6062 * Note that cloudflare env string values are copied by the middleware handler.
6163 */
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 ;
6669 const mode = nextJsEnv ?? "production" ;
6770
6871 if ( nextEnvVars [ mode ] ) {
0 commit comments