Cloudflare
How-Tos
Enviroment Variables

Environment variables

This entry describe the most sensible way to handle your environment variables which works well both during local development and once your application is deployed to Cloudflare Workers.

On the Cloudflare platform, your environment variables can be stored in either "Enviroment variables" (opens in a new tab) or "Secrets" (opens in a new tab). The difference being that Secrets can not be read back from either the dashboard or the CLI after being created.

Local development

While there are multiple ways to set environment variables for local development on the Cloudflare platform (adding them to to your wrangler configuration (opens in a new tab) or to a .dev.vars (opens in a new tab) file) that does not play well with the recommended development workflow as they would not be available while using next dev.

What you should do instead is to use the Next.js .env files (opens in a new tab). By doing so the environment variables will be available on process.env both while running next dev and when running your app locally on a Worker with wrangler dev.

Next.js .env files are environment specific. That is a .env.development will take precedence over a .env file when you use the "development" environment. See the Next.js site for a detailed explanation of the loading order (opens in a new tab).

You should use the NEXTJS_ENV environment variable to select the environment to use when running your app locally on a worker, that's how you would select the "development" environment:

# .dev.vars
NEXTJS_ENV=development

The "production" environment is used by default when NEXTJS_ENV is not explicitly set.

Production

.env and .dev.vars are local files that should not be added to source control. You should instead use the cloudflare dashboard to set your environment variables for production.

Next.js has 2 kinds (opens in a new tab) of environment variables:

  • non-NEXT_PUBLIC_ variables which are only available on the server
  • NEXT_PUBLIC_ variables on the other hand are available to the browser

Those are called runtime environment variables (non-NEXT_PUBLIC_) and buildtime environment variables (NEXT_PUBLIC_) on the Cloudflare paltform.

You can set the runtime environment variables (non-NEXT_PUBLIC_) by following those instructions (opens in a new tab). The build time environment variables (NEXT_PUBLIC_) should be set in the Builds Configuration (opens in a new tab) so that their value can be inlined by the Workers Builds.