Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use ALS for process.env object #98

Closed
wants to merge 8 commits into from
3 changes: 2 additions & 1 deletion packages/cloudflare/src/cli/templates/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any)[Symbol.for("__cloudflare-context__")] = createALSProxy(cloudflareContextALS);

const originalEnv: Partial<typeof process.env> = { ...globalThis.process.env };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to clone this object here? We make a copy of the originalEnv when setting up the ALS.

// @ts-expect-error - populated when we run inside the ALS context
globalThis.process.env = createALSProxy(processEnvALS);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I agree with @vicb to some extent here.
Before any request, there might already be values on process.env, which are being lost by assigning it here.
How about we capture the original process.env somehow and then include that in the initialization of the store below.

E.g.

const originalEnv = globalThis.process.env;
globalThis.process.env = createALSProxy(processEnvALS);
...
export default {
  async fetch(request, env, ctx) {
    return processEnvALS.run({ NODE_ENV: "production", ...originalEnv, ...env }, () => {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to add tests.

(I think we should requires them in the PR template, as well as repro on issue templat - well we have to add those templates first, I can take care of that next week)


Expand All @@ -30,7 +31,7 @@ let requestHandler: NodeRequestHandler | null = null;

export default {
async fetch(request, env, ctx) {
return processEnvALS.run({ NODE_ENV: "production", ...env }, () => {
return processEnvALS.run({ NODE_ENV: "production", ...originalEnv, ...env }, () => {
return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
if (requestHandler == null) {
// Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
Expand Down