edmundhung/remix-cloudflare-template

process is not defined

fmgono opened this issue · 3 comments

can you give me an example how to load env variable from .env ?
already using dotenv but dont know how to use it

thank you

Hi @fmgono! Cloudlfare Worker is not a node environment. So you cannot access it with the node specific syntax (ie. process.env.XXXXX). I would suggest you reading the documentation from Cloudflare for more details.

Basically, you should define the variables on wrangler.toml. But in case of secret, you can continue using .env for local development. It should work out of the box as our development server (miniflare) already did that for you. These secrets can be set using the wrangler CLI for production.

Hi @edmundhung! Thank you for your reply!
So that means I have to separate write separate code while accessing .env between local and production mode ?
example

export const loader: LoaderFunction = ( {request} ) => {
  let VAR_FROM_ENV = process.env === 'development' ? process.env.VAR_FROM_ENV : <I don't know how to access this from loader>
}

can you enlighten me and an example how to do it, please ? I still don't understand how to read and set env at Cloudflare environment

Thank you

There are 2 different approaches to use environment variables dependings on your worker setup - service worker and module worker. The example below works only if you are using module worker (which this template is setup with) which is similar to how cloudlfare pages works.

The adapter receives the environment variables from the fetch function and it will be available first on getLoadContext().

If you are using my template without changing /worker/index.ts, you should have a setup like this below:

getLoadContext(request, env, ctx) {
  return { env, ctx };
}

This is a convention from Remix to pass environment/server specific variables to Remix as context

With the above setup, you should be able to access context on both loader and action, for example:

export const loader: LoaderFunction = ({ request, context }) => {
  let MY_ENV_NAME = context.env.MY_ENV_NAME; // This should works seamlessly on both development and production, as long as you have the variables setup already
}

Hope this helps :) Let me know if you have more questions.