Star on GitHub - 5.8k

Cloudflare

Use Dotenvx with Cloudflare.

Install

Install wrangler and dotenvx.

$ npm install --save-dev wrangler@latest
$ npm install --save-dev @dotenvx/dotenvx

Encrypt

Create .env.production:

# .env.production
HELLO="Production"

Deploy

Deploy it with the dotenvx --secrets-file.

$ npx wrangler deploy --secrets-file <(npx dotenvx get -f .env.production --strict)

That's it. Your Worker reads env.HELLO just like any other Cloudflare secret.

// src/index.js
export default {
  async fetch(request, env) {
    return new Response(`Hello ${env.HELLO}`)
  }
}

Scripts

Add to your scripts for convenience.

{
  "scripts": {
    "deploy": "bash -c 'wrangler deploy --secrets-file <(dotenvx get -f .env.production --strict)'",
    "preview": "bash -c 'wrangler preview --secrets-file <(dotenvx get -f .env.preview --strict)'"
  }
}

Pages

Using pages? It is similar to workers.

$ npx wrangler pages secret bulk <(npx dotenvx get -f .env.production --strict) --project-name my-site
$ npx wrangler pages deploy dist --project-name my-site

Advanced

The above set up is typical for Cloudflare but if you want to get full secrets separation in the spirit of dotenvx you can ship an encrypted .env.txt file to decrypt at runtime.

Install dotenvx.

$ npm install @dotenvx/dotenvx

Encrypt a .env.production.txt file. The .txt extension allows it to be included in the worker as an artifact.

$ npx dotenvx encrypt -f .env.production.txt

Commit to code.

$ git add .env.production.txt
$ git commit -m "encrypt .env.production.txt"

Then inject your encrypted secrets at runtime.

import envSrc from '../.env.production.txt'
import dotenvx from '@dotenvx/dotenvx'

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

export default {
  async fetch(request, env, ctx) {
    return new Response(`Hello ${envx.HELLO}`)
  }
}

Adjust your deploy script to set your production keypair on Cloudflare.

{
  "scripts": {
    "deploy": "bash -c 'wrangler deploy --secrets-file <(dotenvx keypair -f .env.production.txt)'"
  }
}

That's it! This gives you advanced protection.