Encrypt secrets in Cloudflare Workers

Learn how to encrypt your first .env file using Cloudflare Workers and the Dotenvx Node.js SDK.

1. Install

Get the Dotenvx Node.js SDK.

$ npm install @dotenvx/dotenvx
# or
# bun add @dotenvx/dotenvx
# pnpm add @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
◈ encrypted (.env.txt)

3. Inject

Then inject your encrypted secrets at runtime.

src/index.js

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"
},

Production

Set DOTENV_PRIVATE_KEY on Cloudflare and deploy.

cloudflare.com
wrangler deploy