Use dotenvx with Vercel

Use dotenvx with Vercel

Initial setup

Install the necessary web server libraries in the framework of your choice.

npx create-next-app@latest --example hello-world .

Create a simple Hello World program.

// app/page.tsx
export default function Page() {
  return <h1>Hello {process.env.HELLO}</h1>;

Add .vercelignore file.


# vercelignore

Commit to code and deploy to Vercel.

npx vercel@latest deploy --prod

Once deployed, your app will say 'Hello [blank]' as it doesn't have a way to access the environment variable yet. Let's do that next.

Run dotenvx

Install dotenvx.

npm install @dotenvx/dotenvx --save

Preload scripts with dotenvx. This will inject environment variables ahead of any build, start, or dev commands.

"scripts": {
  "dotenvx": "dotenvx",
  "dev": "dotenvx run -- next dev --turbo",
  "build": "dotenvx run -- next build",
  "start": "dotenvx run -- next start"

Add production environment

Create .env.production in the root of your project.

# .env.production

Encrypt production

npm run dotenvx -- set HELLO production -f .env.production

Your .env.production file is now encrypted, and you have a .env.keys file.

#/            public-key encryption for .env files          /
#/       [how it works](     /

# .env.production
#/ private decryption keys. DO NOT commit to source control /
#/     [how it works](       /

# .env.production

We're ready to inject the encrypted .env.production secrets into the app on boot.

Set decryption key

Set DOTENV_PRIVATE_KEY_PRODUCTION on Vercel using the production key in your .env.keys file. We'll use the Vercel cli, but you can also use their dashboard.

npx vercel@latest env add DOTENV_PRIVATE_KEY_PRODUCTION
? What’s the value of DOTENV_PRIVATE_KEY_PRODUCTION? 424d0ea072eb17c6bee9b4b42ff6333513cf128ea3d5d60ccf79246ca7c3f786
✅  Added Environment Variable DOTENV_PRIVATE_KEY_PRODUCTION to Project nodejs-vercel [94ms]


npx vercel@latest deploy --prod

Your app restarts and env is successfully injected using the encrypted contents of .env.production.

$ npx vercel@latest logs
Running "npm run build"

> build
> dotenvx run -- next build

[[email protected]] injecting env (2) from .env.production
   Creating an optimized production build ...
 ✓ Compiled successfully

Visit your url and it says Hello production.

Great job! That's pretty much it. See the bonus section(s) below to go a little deeper.


Try changing the value of .env.production to your name.

npm run dotenvx -- set HELLO Mot

Commit .env.production safely to code and redeploy.