Skip to main content
Version: Next

Authentication Setup

SaaS Developer Templates comes pre-integrated with NextAuth, a powerful library for managing authentication in Next.js applications. Follow this guide to configure authentication for your SaaS project.


Step 1: Install Dependencies

First, ensure that you have NextAuth installed in your project. If not, install it using the following command:

npm install next-auth

Step 2: Configure Authentication Providers

  1. Create a new file at pages/api/auth/[...nextauth].js:

    mkdir -p pages/api/auth
    touch pages/api/auth/[...nextauth].js
  2. Add the following code to pages/api/auth/[...nextauth].js:

    import NextAuth from 'next-auth';
    import GoogleProvider from 'next-auth/providers/google';
    import GithubProvider from 'next-auth/providers/github';

    export default NextAuth({
    providers: [
    GoogleProvider({
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    GithubProvider({
    clientId: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
    ],
    secret: process.env.NEXTAUTH_SECRET,
    callbacks: {
    async session({ session, token }) {
    session.user.id = token.sub;
    return session;
    },
    },
    });
  3. Update your .env file with the credentials for your authentication 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

    NEXTAUTH_SECRET=your-random-secret

    Replace your-google-client-id, your-google-client-secret, etc., with your actual credentials.


Step 3: Add Authentication to Your App

  1. Use the SessionProvider component from NextAuth to wrap your app:

    Open pages/_app.js or pages/_app.tsx and add:

    import { SessionProvider } from 'next-auth/react';

    export default function MyApp({ Component, pageProps: { session, ...pageProps } }) {
    return (
    <SessionProvider session={session}>
    <Component {...pageProps} />
    </SessionProvider>
    );
    }
  2. Protect specific pages or components using the useSession hook:

    import { useSession, signIn, signOut } from 'next-auth/react';

    export default function ProtectedPage() {
    const { data: session } = useSession();

    if (!session) {
    return (
    <div>
    <p>You need to sign in to access this page.</p>
    <button onClick={() => signIn()}>Sign In</button>
    </div>
    );
    }

    return (
    <div>
    <p>Welcome, {session.user.name}!</p>
    <button onClick={() => signOut()}>Sign Out</button>
    </div>
    );
    }

Step 4: Customizing Authentication

NextAuth provides extensive customization options:

  • Callbacks: Customize session behavior.
  • JWT Tokens: Add custom claims or manage token lifecycle.
  • Database: Store user sessions in a database by configuring Prisma or another database of your choice.

Learn more in the NextAuth documentation.


Troubleshooting

  • Provider Errors: Double-check your API keys and secret configurations.
  • Environment Variables: Ensure .env variables are loaded correctly (restart the server if necessary).
  • NextAuth Secret: Generate a secure secret using openssl rand -base64 32 if needed.

Your authentication setup is now complete! 🎉
Proceed to the next step: Database Setup.