Next.js
Encrypt a .env file in Next.js with Dotenvx, commit it safely, and load its secrets at runtime.
1. Install
Get the Dotenvx Node.js SDK and
@dotenvx/next-env.
$ npm install @dotenvx/dotenvx
$ npm install @dotenvx/next-env
Override
@next/env in your package.json.
{
...
"overrides": {
"@next/env": "npm:@dotenvx/next-env"
}
}
2. Encrypt
Encrypt your .env file.
$ npx dotenvx encrypt
3. Inject
Your encrypted secrets are automatically injected and readable in Next.js.
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