Cloudflare Workers

Encrypt a .env file in Cloudflare Workers with the Dotenvx Node.js SDK and load its secrets at runtime.

1. Install

Get the Dotenvx Node.js SDK.
$ npm install @dotenvx/dotenvx

2. Encrypt

Encrypt your .env.txt file. Use .env.txt so it can be included in the worker artifact deploy.
$ npx dotenvx encrypt -f .env.txt

3. Inject

Then inject your encrypted secrets at runtime.
import envSrc from '../.env.txt'
import dotenvx from '@dotenvx/dotenvx'

const config = dotenvx.config({ envs: [{ type: 'env', value: envSrc, privateKeyName: 'DOTENV_PRIVATE_KEY' }] })
const envx = config.parsed

export default {
  async fetch(request, env, ctx) {
    return new Response(`Hello ${envx.HELLO}`)
  }
}
"scripts": {
  "deploy": "wrangler deploy",
  "dev": "wrangler dev --var $(dotenvx keypair -f .env.txt --format=colon)",
  "start": "wrangler dev --var $(dotenvx keypair -f .env.txt --format=colon)",
  "test": "vitest"
}