Closed mondaychen closed 1 week ago
we spent some time last week on this topic. Cloudflare workers don't use process.env, rather it picks the vars you add in [vars] section of wrangler.toml or .dev.vars and uses them as constants. Cloudflare workers pick these vars on every run (or execution.
so, using them as process.env.xxx is not possible.
what we did in our project is
declare global {
namespace NodeJS {
interface ProcessEnv extends CloudflareEnv {}
}
}
export type {};
2. added a line in cloudflare.ts
process.env = env // this is the env picked from vars
3. use process.env everywhere as expected.
I have the .dev.vars created but on printing the variables using process.env.variable_name I don't see the value being picked.
I have the .dev.vars created but on printing the variables using process.env.variable_name I don't see the value being picked.
Try adding export const runtime = 'edge'
to your file where you are reading the variable. That should fix it
Hi there! As a Cloudflare newbie (trying to look for other alternatives than Vercel), I'm being puzzled by the same thing. I read everywhere about how it's not possible to use CF env vars on Next's dev mode and how export const runtime = 'edge'
is required but here and here the code is not using either Cloudflare's dev mode, edge runtime or anything and just works calling process.env
. Anyone knows how is that achieved?
@guidovizoso These files are invoked from other route pages which have export const runtime = 'edge'
. The db file for example is imported here and here. The second file doesn't have edge runtime, because it is not used directly but in other API routes like this one which has edge runtime.
Similarly the auth methods are imported in this page which have edge runtime.
If you remove edge runtime from all these files, you would not be able to read those env variables
@vijaynandwani Thanks for the insight! I'm still getting used to the CF way of using Next, that's super helpful
I've been working on my project based on this stack for a while. Now I think I can answer my original questions:
.dev.vars
is a Cloudflare / wrangler convention and will be picked up on files running on "edge runtime". For other use cases, you can write variables in .env
and NextJS will pick it up.
Thanks for the stack! Love it.
I have some questions regarding the environmental variables.
.dev.vars
for you. Why is it not.env
file that many other next.js project use?Does that mean we should use different files for different env vars? Like OpenAI key should be in a file called env.AI?