# The complete guide to authentication on Vercel

**Author:** Michael Merrill

---

Authentication is the most common friction point when deploying applications to Vercel. This guide covers everything from basic NextAuth/Auth.js setup to enterprise OAuth2 patterns, helping you avoid the "works locally but fails on Vercel" problem.

## NextAuth/Auth.js setup on Vercel

NextAuth.js (now Auth.js) is the most popular authentication library for Next.js applications. Setting it up on Vercel requires attention to environment variables and URL configuration.

### Required environment variables

Configure these variables in your Vercel project settings:

- `NEXTAUTH_SECRET` - A random string used to encrypt tokens and cookies. Generate with `openssl rand -base64 32`
  
- `NEXTAUTH_URL` - Your production URL (e.g., `https://your-app.vercel.app`). On Vercel, this is automatically set for production but must be configured for preview deployments.
  

### The NEXTAUTH\_URL gotcha

This is the most common source of auth failures on Vercel. In production, Vercel automatically infers the correct URL, so you don't need to set `NEXTAUTH_URL`. However, preview deployments get unique URLs, which causes callback URL mismatches with OAuth providers.

**Solutions:**

1. Use `VERCEL_URL` for dynamic URL detection in your auth configuration
   
2. Add wildcard callback URLs to your OAuth provider (e.g., `https://*.vercel.app/api/auth/callback/*`)
   
3. Use branch-specific environment variables in Vercel for preview deployments with a stable domain
   

### Google and GitHub provider setup

**For Google OAuth:**

1. Create credentials in Google Cloud Console
   
2. Add authorized redirect URIs: `https://your-domain.com/api/auth/callback/google`
   
3. Set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` in Vercel
   

**For GitHub OAuth:**

1. Create an OAuth App in GitHub Developer Settings
   
2. Set callback URL: `https://your-domain.com/api/auth/callback/github`
   
3. Set `GITHUB_ID` and `GITHUB_SECRET` in Vercel
   

## OAuth2 for enterprise integrations

Enterprise customers building agents and integrations often need OAuth2 patterns for proprietary systems like banking APIs or internal SaaS platforms.

### Custom OAuth2 provider pattern

When integrating with proprietary OAuth2 systems, define a custom provider in your Auth.js configuration:

1. Configure the authorization endpoint, token endpoint, and userinfo endpoint
   
2. Map the provider's user profile to your application's user model
   
3. Handle token refresh for long-lived sessions
   

### MCP server authentication

For Model Context Protocol (MCP) servers deployed on Vercel, implement OAuth authorization using the `withMcpAuth` wrapper. This pattern validates bearer tokens, checks required scopes, and returns authenticated user information to your handlers.

## Securing Server Actions

Server Actions introduce new security considerations. Unlike API routes, Server Actions can be invoked from client components, creating potential attack vectors.

### Authentication checks

Always verify the user's session at the start of every Server Action:

1. Call `getServerSession()` or your auth library's equivalent
   
2. Return early or throw an error if unauthenticated
   
3. Verify user permissions for the specific action
   

### CSRF protection

Next.js Server Actions have built-in CSRF protection through origin checking. The framework automatically validates that requests originate from your domain. However, ensure your `next.config.js` doesn't disable these protections.

### Rate limiting

Protect sensitive Server Actions from abuse:

- Use Vercel's Edge Config with KV for distributed rate limiting
  
- Implement per-user and per-IP limits
  
- Consider using Vercel's Firewall rules for additional protection
  

### Server reference security

Server Actions create server references that can be discovered by attackers. Never rely on obscurity:

- Treat every Server Action as a public API endpoint
  
- Validate all inputs server-side
  
- Use Zod or similar libraries for runtime type checking
  

## Troubleshooting: works locally, fails on Vercel

Use this matrix to diagnose common authentication failures:

**Symptom: OAuth callback fails with "redirect\_uri\_mismatch"**

- Cause: NEXTAUTH\_URL mismatch or callback URL not registered with OAuth provider
  
- Fix: Add your Vercel domain to OAuth provider's allowed redirect URIs
  

**Symptom: Session is null after successful login**

- Cause: NEXTAUTH\_SECRET not set or different between environments
  
- Fix: Ensure NEXTAUTH\_SECRET is set in Vercel environment variables for all environments
  

**Symptom: Infinite redirect loop on sign-in**

- Cause: Cookie domain mismatch or secure cookie issues
  
- Fix: Ensure your app is served over HTTPS and cookie settings match your domain
  

**Symptom: "CSRF token mismatch" error**

- Cause: Session cookie not persisting between requests
  
- Fix: Check cookie settings, particularly SameSite and Secure attributes
  

**Symptom: Auth works on main branch but fails on preview**

- Cause: Preview deployments have unique URLs not registered with OAuth provider
  
- Fix: Use wildcard callback URLs or configure branch-specific environment variables
  

## v0 to Vercel deployment auth flow

When deploying a v0-generated app with authentication to Vercel:

1. **Export your project** - Deploy directly to Vercel from v0's interface
   
2. **Configure environment variables** - Add NEXTAUTH\_SECRET and provider credentials in Vercel project settings
   
3. **Update OAuth providers** - Add your new Vercel domain to allowed callback URLs
   
4. **Test authentication** - Verify sign-in and sign-out flows work correctly
   
5. **Configure preview environments** - Set up auth for preview deployments if needed
   

**Common v0 auth issues:**

- v0 uses placeholder environment variables - replace them with real credentials
  
- Database connections may need updating for production
  
- Auth callbacks expect your production domain, not localhost
  

## Summary

Authentication on Vercel requires attention to environment configuration, especially around NEXTAUTH\_URL and callback URLs. For enterprise OAuth2 integrations, define custom providers and handle token refresh. Secure your Server Actions by validating sessions, implementing rate limiting, and treating every action as a public endpoint. When issues arise, check environment variables first - they're the root cause of most "works locally, fails on Vercel" problems.

---

[View full KB sitemap](/kb/sitemap.md)
