Encrypt secrets in Next.js
Learn how to encrypt your first .env file using Next.js and the Dotenvx Node.js SDK.
Prerequisites
To get the most out of this guide, you'll need to:
- Install dotenvx
- Create your account (optional)
1. Install
Get the Dotenvx Node.js SDK.
npm install @dotenvx/dotenvx
2. Encrypt env file
Encrypt your .env file.
$ terminal
npx dotenvx encrypt
3. Inject secrets
Preface Next.js scripts with dotenvx run -- and read your env values in Next.js.
package.json
{
"scripts": {
"dev": "dotenvx run -- next dev",
"build": "dotenvx run -- next build",
"start": "dotenvx run -- next start"
}
}
src/app/api/route.tsx
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({
HELLO: process.env.HELLO,
})
}
Add src/instrumentation.js so Vercel serverless functions load environment variables at runtime.
src/instrumentation.js
export async function register() {
const { config } = await import('@dotenvx/dotenvx')
config()
}