Encrypt secrets in Next.js

Learn how to encrypt your first .env file using Next.js and Dotenvx.

1. Install

Get the Dotenvx Node.js SDK and @dotenvx/next-env.

$ npm install @dotenvx/dotenvx
$ npm install @dotenvx/next-env
# or
# bun add @dotenvx/dotenvx
# bun add @dotenvx/next-env
# pnpm add @dotenvx/dotenvx
# pnpm add @dotenvx/next-env

Override @next/env in your package.json.

package.json

{
  ...
  "overrides": {
    "@next/env": "npm:@dotenvx/next-env"
  }
}

2. Encrypt

Encrypt your .env file.

$ npx dotenvx encrypt
◈ encrypted (.env)

3. Inject

Your encrypted secrets are automatically injected and readable in Next.js.

src/app/api/route.tsx

import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json({
    HELLO: process.env.HELLO,
  })
}

Troubleshooting

Not taking effect? NPM can be inconsistent with overrides. Delete package-lock.json, node_modules, and reinstall.

rm -rf node_modules package-lock.json
npm install

Production

Set DOTENV_PRIVATE_KEY on Vercel and deploy.

vercel.com