Authentication
Set up authentication for your SaaS application.
This SaaS boilerplate uses NextAuth.js for authentication, with support for Google OAuth and Magic Link (email-based) authentication. The authentication system is already integrated with Prisma for storing user data.
Authentication Setup
Set up Google OAuth
- Go to Google Cloud Console
- Go to Sidebar → APIs & Services → Credentials → Create project → Create credentials → OAuth Client IDs → select Web application
- Set the authorized redirect URI to:
http://localhost:3000/api/auth/callback/google
https://your-domain/api/auth/callback/google
for production replace with your domain. - Copy the Client ID and Client Secret
- Add Credentials to
.env
fileGOOGLE_CLIENT_ID="your-client-id"GOOGLE_CLIENT_SECRET="your-client-secret"AUTH_SECRET="your-auth-secret"AUTH_SECRET you can use any strong secret key
Magic link Setup
Setup Email
Authentication setup on your app
- Authentication Schema
prisma/schema.prisma
- Authentication API endpoint
app/api/auth/[...nextauth]/route.ts
- Google & Email Provider
lib/auth.ts
- Session Provider
app/providers.tsx
- Login and signup page
app/login/page.tsx
- Dashboard (protected page)
app/(protecting)/dashboard/layout
Captcha Setup (Optional)
Why use Captcha?
Enhance your authentication security by implementing Google reCAPTCHA to protect against automated attacks and spam. This setup integrates seamlessly with your existing authentication flow.
Step 1: Create a Google reCAPTCHA Account
- Go to the Google reCAPTCHA Admin Console
- Click Create to register a new site
- Select reCAPTCHA v2 with the "I'm not a robot" checkbox option
- Add your domain(s):
localhost
for development and your production domain - Accept the terms of service and submit
- Copy your Site Key (for frontend) and Secret Key (for backend)
Step 2: Add Environment Variables
Add your reCAPTCHA credentials to your .env
file:
NEXT_PUBLIC_RECAPTCHA_SITE_KEY="your-site-key"RECAPTCHA_SECRET_KEY="your-secret-key"
Step 3: Add Captcha to your app
You can find this complete code setup in the captcha.md
file in your project root.
TypeScript Support
If you encounter TypeScript errors with the reCAPTCHA component, create a type definition file at (if you not getting error then skip this) types/react-google-recaptcha.d.ts
:
declare module 'react-google-recaptcha' {import * as React from 'react';interface ReCAPTCHAProps {sitekey: string;onChange?: (token: string | null) => void;onExpired?: () => void;onErrored?: () => void;grecaptcha?: any;size?: 'compact' | 'normal' | 'invisible';theme?: 'dark' | 'light';badge?: 'bottomright' | 'bottomleft' | 'inline';tabindex?: number;hl?: string;}export default class ReCAPTCHA extends React.Component<ReCAPTCHAProps> {}}
Make sure your tsconfig.json
includes the types directory in the include array.