Find code examples for this guide on GitHub (Next.js and Astro).
Initial setup
Create a Next.js app (or Astro), ignore .env.keys, and deploy.
npx create-next-app@latest --example hello-world .
// app/page.tsx
export default function Page() {
return <h1>Hello {process.env.HELLO}</h1>;
}
# .vercelignore
.env.keys
# .gitignore
!.env.production
.env.keys
npx vercel@latest deploy --prod
Run dotenvx
npm install @dotenvx/dotenvx --save
For Next.js, swap process.env for dotenvx.get.
// app/page.tsx
import * as dotenvx from '@dotenvx/dotenvx';
export default async function Page() {
return <h1>Hello {await dotenvx.get('HELLO')}</h1>;
}
Add dotenvx to your scripts.
"scripts": {
"dotenvx": "dotenvx",
"dev": "dotenvx run -- next dev --turbo",
"build": "dotenvx run -- next build",
"start": "dotenvx run -- next start"
}
Encrypt production
# .env.production
HELLO="production"
npm run dotenvx -- set HELLO production -f .env.production
Commit .env.production. Do not commit .env.keys.
Set decryption key
Set DOTENV_PRIVATE_KEY_PRODUCTION on Vercel from your .env.keys file.
npx vercel@latest env add DOTENV_PRIVATE_KEY_PRODUCTION
npx vercel@latest deploy --prod
Your build injects env from the encrypted .env.production file.