Next.js
Encrypt a .env file in Next.js with Dotenvx, commit it safely, and load its secrets at runtime.
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, then run npm install again to apply the override.
{
...
"overrides": {
"@next/env": "npm:@dotenvx/next-env"
}
}
Encrypt
Encrypt your .env file.
$ npx dotenvx encrypt
Commit the encrypted
.env file. Keep .env.keys out of git and deployment uploads; it contains your private decryption key.
Inject
Your encrypted secrets are automatically injected and readable through
process.env in Next.js. Use your normal next dev, next build, and next start commands.
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({
HELLO: process.env.HELLO,
})
}
This is the canonical Next.js setup, including apps hosted on Vercel.
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