NextAuth.js (now Auth.js) requires a secret for encrypting JWTs, hashing tokens, and generating CSRF tokens. This secret is essential for the security of your authentication system.
What is NextAuth NEXTAUTH_SECRET?
NEXTAUTH_SECRET is used by NextAuth.js to encrypt JWT tokens, hash email verification tokens, and generate CSRF tokens. In production, this environment variable is required and NextAuth.js will throw an error if it's not set.
Key Requirements
- At least 32 characters recommended
- Must be random and unpredictable
- Required in production environments
- URL-safe characters preferred
How to Use
Add to your .env.local file:
```
NEXTAUTH_SECRET=your_generated_secret_here
NEXTAUTH_URL=http://localhost:3000
```
Or generate using OpenSSL:
```bash
openssl rand -base64 32
```
The secret is automatically used by NextAuth.js when configured:
```javascript
// pages/api/auth/[...nextauth].js
export default NextAuth({
// NEXTAUTH_SECRET is read automatically
providers: [...]
})
```Best Practices
- Always set NEXTAUTH_SECRET in production
- Use different secrets for development and production
- Set NEXTAUTH_URL for proper callback URLs
- Consider using Auth.js v5 for App Router support
- Enable database sessions for better security
Common Mistakes to Avoid
- ✗Not setting NEXTAUTH_SECRET in production
- ✗Using weak or predictable secrets
- ✗Forgetting to set NEXTAUTH_URL
- ✗Not configuring proper callback URLs
- ✗Mixing up environment variable names