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 32After 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:
- Go to GitHub Developer Settings
- Click on "OAuth Apps" and then "New OAuth App"
- Fill in the registration form:
- Application name: Your application name (e.g., "MkSaaS")
- Homepage URL: Your site's URL (e.g.,
https://YOUR-DOMAIN.comorhttp://localhost:3000for local development) - Application description: A brief description of your application
- Authorization callback URL: Set this to
https://YOUR-DOMAIN.com/api/auth/callback/github(orhttp://localhost:3000/api/auth/callback/githubfor local development)
- Click "Register application"
- After registration, you'll see your Client ID
- Click "Generate a new client secret" to create your Client Secret
- 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"- Ensure
website.tsxfileauth.enableGithubLoginis set totrue
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:
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Go to
Credentialsin the left sidebar - Click
Create Credentialsand selectOAuth client ID - 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 Continuethrough each section
- 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.comorhttp://localhost:3000) - Authorized redirect URIs: Add
https://YOUR-DOMAIN.com/api/auth/callback/google(orhttp://localhost:3000/api/auth/callback/googlefor local development)
- 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"- Ensure
website.tsxfileauth.enableGoogleLoginis set totrue
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:
- Follow the requirements of Email Configuration document to configure email service
- Update
website.tsxfile, setenableCredentialLogintotrue, and set email provider and default sender email address, for example:
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>;
}
MkSaaS Docs