LogoMkSaaS Docs
LogoMkSaaS Docs
HomepageIntroductionCodebaseVideo TutorialsGetting StartedEnvironment Setup
Configuration

Integrations

DatabaseAuthenticationEmailNewsletterStoragePaymentCreditsCron JobsAIAnalyticsNotificationCaptchaChatboxAffiliates

Customization

MetadataFontsThemesImagesi18nBlogDocsComponentsCustom PagesLanding PageUser ManagementAPI Key Management

Codebase

IDE SetupProject StructureFormatting & LintingUpdating the Codebase
X (Twitter)

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

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 environment variables file:

BETTER_AUTH_SECRET="YOUR-BETTER-AUTH-SECRET"

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 environment variables file:
GITHUB_CLIENT_ID="YOUR-GITHUB-CLIENT-ID"
GITHUB_CLIENT_SECRET="YOUR-GITHUB-CLIENT-SECRET"
  1. Ensure website.tsx file auth.enableGithubLogin is set to true
src/config/website.tsx
auth: {
  enableGithubLogin: true,
}

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.

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 (website name, user support email, developer contact)
    • Add authorized domains including your website domain
    • Click Save and Continue through each section
  6. Return to "Credentials" and create the OAuth Client ID:
    • Application type: Web application
    • Name: Your website 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 environment variables file:
GOOGLE_CLIENT_ID="YOUR-GOOGLE-CLIENT-ID"
GOOGLE_CLIENT_SECRET="YOUR-GOOGLE-CLIENT-SECRET"
  1. Ensure website.tsx file auth.enableGoogleLogin is set to true
src/config/website.tsx
auth: {
  enableGoogleLogin: true,
}

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.

Configure Credential Login

To enable credential login, follow these steps:

  1. Follow the requirements of Email Configuration document to configure email service
  2. Update website.tsx file, set enableCredentialLogin to true, and set email provider and default sender email address, for example:
src/config/website.tsx
export const websiteConfig = {
  // ...other config
  auth: {
    enableCredentialLogin: true,
  },
  mail: {
    provider: 'resend', // Email provider to use
    fromEmail: 'support@example.com', // Default sender email address
  },
  // ...other config
}

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


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();

Server-Side Usage

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, you can check the user role in the session:

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>;
}

Video Tutorial

Next Steps

Email

Configure email services

Newsletter

Configure newsletter

Database

Configure database

Environment Setup

Configure environment variables

Table of Contents

Setup
Generate Better Auth Secret Key
Configure GitHub OAuth
Configure Google OAuth
Configure Credential Login
Client-Side Usage
Accessing Session Data
Authentication Operations
Server-Side Usage
Server-Side Route Protection
Admin Route Protection
Video Tutorial
Next Steps