LogoMkSaaS Docs

Authentication

Learn how to set up and use authentication with Better Auth in MkSaaS

MkSaaS uses Better Auth for authentication, providing a flexible and secure system with multiple authentication methods, session management, and role-based access control.

Setup

To set up authentication in MkSaaS, follow these steps to configure the necessary environment variables:

1. Generate Better Auth Secret Key

The BETTER_AUTH_SECRET is a random string used for encryption and generating hashes. You can generate a secret key using the OpenSSL command:

openssl rand -base64 32

After generating your secret key, add it to your .env file:

BETTER_AUTH_SECRET="your_generated_secret_key"

2. Configure GitHub OAuth

To enable GitHub authentication, you need to register your application:

  1. Go to GitHub Developer Settings
  2. Click on "OAuth Apps" and then "New OAuth App"
  3. Fill in the registration form:
    • Application name: Your application name (e.g., "MkSaaS")
    • Homepage URL: Your site's URL (e.g., https://your-domain.com or http://localhost:3000 for local development)
    • Application description: A brief description of your application
    • Authorization callback URL: Set this to https://your-domain.com/api/auth/callback/github (or http://localhost:3000/api/auth/callback/github for local development)
  4. Click "Register application"
  5. After registration, you'll see your Client ID
  6. Click "Generate a new client secret" to create your Client Secret
  7. Copy both values and add them to your .env file:
GITHUB_CLIENT_ID="your_github_client_id"
GITHUB_CLIENT_SECRET="your_github_client_secret"

Create two different OAuth applications in GitHub - one for production and one for development. Never use the same OAuth application for both environments as they require different callback URLs.

3. Configure Google OAuth

To enable Google authentication, follow these steps to obtain client credentials:

  1. Go to the Google Cloud Console
  2. Create a new project or select an existing one
  3. Go to "Credentials" in the left sidebar
  4. Click "Create Credentials" and select "OAuth client ID"
  5. If this is your first time, you may need to configure the OAuth consent screen:
    • User Type: Choose "External"
    • Fill in the required information (app name, user support email, developer contact)
    • Add authorized domains including your application domain
    • Click "Save and Continue" through each section
  6. Return to "Credentials" and create the OAuth client ID:
    • Application type: Web application
    • Name: Your application name
    • Authorized JavaScript origins: Add your domain (e.g., https://your-domain.com or http://localhost:3000)
    • Authorized redirect URIs: Add https://your-domain.com/api/auth/callback/google (or http://localhost:3000/api/auth/callback/google for local development)
  7. Click "Create", copy the provided Client ID and Client Secret, add them to the .env file:
GOOGLE_CLIENT_ID="your_google_client_id"
GOOGLE_CLIENT_SECRET="your_google_client_secret"

Create two different OAuth applications in Google Cloud Console - one for production and one for development. Never use the same OAuth application for both environments as they require different callback URLs.

If you are setting up the environment, now you can go back to the Environment Setup guide and continue. The rest of this guide can be read later.

Environment Setup

Set up environment variables


Authentication System Structure

The authentication system in MkSaaS is designed with the following components:

auth.ts
auth-client.ts

This structure follows Next.js best practices with the App Router and handles internationalization through the locale parameter.

Core Features

  • Email and password authentication with email verification
  • Password reset functionality
  • Social login providers (Google, GitHub)
  • Account linking between different authentication methods
  • User management (including admin functionality)
  • Session management with cookie-based caching
  • Automatic newsletter subscription on registration (optional)

Client-Side Usage

Accessing Session Data

In client components, you can access the user's session data using the useSession hook:

'use client';
 
import { useSession } from '@/lib/auth-client';
 
export function ProfileButton() {
  const { data: session, isPending } = useSession();
  
  if (isPending) {
    return <div>Loading...</div>;
  }
  
  if (session) {
    return (
      <div>
        <p>Welcome, {session.user.name}!</p>
        <button onClick={() => signOut()}>Sign out</button>
      </div>
    );
  }
  
  return (
    <button onClick={() => signIn.social({ provider: 'google' })}>
      Sign in
    </button>
  );
}

Authentication Operations

The auth client provides methods for common authentication operations:

import { signIn, signOut } from '@/lib/auth-client';
 
// Sign in with email and password
signIn.emailAndPassword({
  email: 'user@example.com',
  password: 'password123',
});
 
// Sign in with social provider
signIn.social({
  provider: 'google',
});
 
// Sign out
signOut();

Protecting Routes

Server-Side Route Protection

In server components, you can protect routes by checking the session:

import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
 
export default async function ProtectedPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  
  if (!session?.user) {
    redirect('/auth/login');
  }
  
  return <div>Protected content</div>;
}

Admin Route Protection

For admin-only routes:

import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
 
export default async function AdminPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  
  if (!session?.user || session.user.role !== 'admin') {
    redirect('/auth/login');
  }
  
  return <div>Admin content</div>;
}

Error Handling

Better Auth supports error handling and redirection:

onAPIError: {
  errorURL: '/auth/error',
  onError: (error, ctx) => {
    console.error('auth error:', error);
  },
},

Best Practices

  1. Require Email Verification: Always require email verification for new users
  2. Provide Multiple Authentication Methods: Offer both email/password and social logins
  3. Use Secure Session Settings: Configure appropriate session timeouts and cookie security
  4. Handle Errors Gracefully: Provide user-friendly error messages and fallbacks
  5. Protect Sensitive Routes: Implement proper authorization checks on both client and server
  6. Keep Auth Libraries Updated: Regularly update dependencies
  7. Consider Different User Roles: Implement proper role-based access controls

Next Steps

Now that you understand how authentication works in MkSaaS, explore these related integrations: