A complete Next.js application with authentication using NextAuth.js, MongoDB, and JWT tokens. Features OAuth providers (Google, GitHub) and magic link authentication via Brevo email service.
AuthPlate is a production-ready starter template for building Next.js applications with authentication. Get started quickly with MongoDB integration, JWT tokens, and security features built-in.
- π¨ Beautiful Landing Page - Modern, responsive homepage with AuthPlate branding
- π JWT-based Authentication - Stateless authentication with JSON Web Tokens
- ποΈ MongoDB Integration - User data stored in MongoDB
- π OAuth Providers - Google and GitHub authentication
- π§ Magic Link Authentication - Passwordless email authentication via Brevo
- β‘ TypeScript Support - Full TypeScript implementation
- π¨ Tailwind CSS - Modern, responsive UI with beautiful components
- π‘οΈ Protected Routes - Dashboard with authentication checks
- π Security Features - Rate limiting, CSRF protection, secure cookies
- π± Mobile Responsive - Works perfectly on all devices
- Node.js 18+
- MongoDB database (local or MongoDB Atlas)
- Google OAuth credentials
- GitHub OAuth credentials
- Brevo account for email service
git clone <your-repo-url>
cd nextjs-betterauth-mongodb
npm installCopy the example environment file and fill in your credentials:
cp env.example .env.localUpdate .env.local with your actual values:
# MongoDB
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database?retryWrites=true&w=majority
# NextAuth.js
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key-here
# OAuth Providers
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
# Brevo Email Configuration
EMAIL_SERVER_HOST=smtp-relay.brevo.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-brevo-username
EMAIL_SERVER_PASSWORD=your-brevo-smtp-key
EMAIL_FROM=noreply@yourdomain.com- Go to Google Cloud Console
- Create a new project or select existing
- Enable Google+ API
- Create OAuth 2.0 credentials
- Add
http://localhost:3000/api/auth/callback/googleto authorized redirect URIs
- Go to GitHub Developer Settings
- Create a new OAuth App
- Set Authorization callback URL to
http://localhost:3000/api/auth/callback/github
- Create a Brevo account
- Go to SMTP & API settings
- Create an SMTP key
- Use the SMTP credentials in your environment variables
Brevo Pricing:
- Free Plan: 300 emails/day (β9,000/month) - Perfect for development
- Lite Plan: $25/month for 20,000 emails
- Cost per magic link: ~$0.00125 (much cheaper than alternatives)
- Create account at MongoDB Atlas
- Create a new cluster
- Get your connection string
- Add your IP to whitelist
- Install MongoDB locally
- Start MongoDB service
- Use
mongodb://localhost:27017/your-database
npm run devVisit http://localhost:3000 to see the beautiful AuthPlate landing page and start building your authenticated application.
src/
βββ app/
β βββ api/auth/[...nextauth]/route.ts # NextAuth.js API route
β βββ auth/
β β βββ signin/page.tsx # Sign-in page
β β βββ verify-request/page.tsx # Magic link verification
β β βββ error/page.tsx # Authentication errors
β βββ dashboard/page.tsx # Protected dashboard
β βββ layout.tsx # Root layout
β βββ page.tsx # Beautiful landing page with AuthPlate branding
β βββ providers.tsx # Session provider
β βββ error.tsx # Global error page
β βββ not-found.tsx # 404 page
βββ components/
β βββ AuthButton.tsx # Authentication button component
β βββ AuthWrapper.tsx # Authentication wrapper component
β βββ Spinner.tsx # Loading spinner component
βββ lib/
β βββ auth.ts # NextAuth.js configuration
β βββ mongodb.ts # MongoDB connection
β βββ env.ts # Environment validation
β βββ logger.ts # Logging utilities
β βββ security.ts # Security utilities
β βββ validation.ts # Input validation
βββ middleware.ts # Rate limiting and security middleware
βββ types/
βββ next-auth.d.ts # NextAuth type definitions
- User clicks "Sign in with Google/GitHub"
- Redirected to provider's OAuth page
- User authorizes the application
- Provider redirects back with authorization code
- NextAuth.js exchanges code for user info
- User data stored in MongoDB
- JWT token created and stored in cookie
- User enters email address
- NextAuth.js sends magic link via Brevo
- User clicks link in email
- Link contains verification token
- Token verified and user authenticated
- JWT token created and stored in cookie
- Modern Design: Clean, professional homepage with AuthPlate branding
- Feature Showcase: Highlights all authentication capabilities
- Responsive: Works perfectly on desktop, tablet, and mobile
- Call-to-Action: Clear sign-in buttons and navigation
- Stateless: No server-side sessions
- Secure: Tokens signed with secret key
- Customizable: User ID included in token
- Expirable: Tokens can have expiration
- Automatic: NextAuth.js handles user storage
- Flexible: Stores users, accounts, sessions
- Scalable: Works with MongoDB Atlas
- Type-safe: Full TypeScript support
- Passwordless: No password storage required
- Secure: Time-limited magic links
- Cost-effective: Brevo free tier for development
- Reliable: Professional email delivery
- Rate Limiting: Prevents abuse with configurable limits
- CSRF Protection: Built-in CSRF token validation
- Secure Cookies: HttpOnly, SameSite, and Secure flags
- Input Validation: Comprehensive validation for all inputs
- Push code to GitHub
- Connect to Vercel
- Add environment variables
- Deploy
- Update
NEXTAUTH_URLfor production - Ensure MongoDB is accessible
- Configure OAuth redirect URIs for production domain
- MongoDB Atlas: Free tier (512MB)
- Brevo: 300 emails/day free
- OAuth: Free for all providers
- Total: $0/month
- MongoDB Atlas: $9/month (2GB)
- Brevo: $25/month (20,000 emails)
- OAuth: Free
- Total: ~$34/month
- MongoDB Atlas: $25+/month
- Brevo: $65+/month
- OAuth: Free
- Total: $90+/month
The landing page is located in src/app/page.tsx and features:
- Hero Section: Main headline and call-to-action
- Features Grid: Showcase of authentication capabilities
- CTA Section: Additional sign-up prompts
- Footer: Branding and links
// In src/lib/auth.ts
import DiscordProvider from 'next-auth/providers/discord'
providers: [
// ... existing providers
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
}),
]// In src/lib/auth.ts
EmailProvider({
// ... existing config
sendVerificationRequest: async ({ identifier, url, provider }) => {
// Custom email sending logic
},
})// In src/lib/auth.ts
callbacks: {
async signIn({ user, account, profile }) {
// Custom sign-in logic
return true
},
async jwt({ token, user, account }) {
// Custom JWT token logic
return token
},
}// In src/middleware.ts
const RATE_LIMIT = {
windowMs: 15 * 60 * 1000, // 15 minutes
maxRequests: 100, // Adjust as needed
authMaxRequests: 100, // Adjust as needed
}-
MongoDB Connection Error
- Check connection string
- Verify IP whitelist (Atlas)
- Ensure database exists
-
OAuth Provider Errors
- Verify client ID/secret
- Check redirect URIs
- Ensure APIs are enabled
-
Email Not Sending
- Verify Brevo credentials
- Check SMTP settings
- Test with different email
-
JWT Token Issues
- Ensure NEXTAUTH_SECRET is set
- Check token expiration
- Verify callback URLs
-
Rate Limiting Issues
- Check middleware configuration
- Verify rate limit settings
- Clear browser cache if needed
- NextAuth.js Documentation
- MongoDB Atlas Documentation
- Brevo Documentation
- OAuth 2.0 Specification
- Tailwind CSS Documentation
-
Clone the repository
git clone <your-repo-url> cd nextjs-betterauth-mongodb npm install
-
Set up environment variables
cp .env.example .env.local # Edit .env.local with your credentials -
Run the development server
npm run dev
-
Visit the AuthPlate landing page Open http://localhost:3000 to see your beautiful authentication starter!
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
AuthPlate - The complete Next.js authentication starter template. Built with β€οΈ for developers who want to focus on building their application, not authentication.
