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:
- Create your account (optional)
1. Install
Get the Dotenvx Node.js SDK.
$ npm install @dotenvx/dotenvx
# or
# bun add @dotenvx/dotenvx
# pnpm add @dotenvx/dotenvx
# yarn add @dotenvx/dotenvx
2. Encrypt
Encrypt your .env file.
npx dotenvx encrypt
3. Inject
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()
}