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
Please 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:
- 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.com
orhttp://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
(orhttp://localhost:3000/api/auth/callback/github
for 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
.env
file:
GITHUB_CLIENT_ID="your_github_client_id"
GITHUB_CLIENT_SECRET="your_github_client_secret"
- Ensure
website.tsx
fileauth.enableGithubLogin
is 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.
3. 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
Credentials
in the left sidebar - Click
Create Credentials
and 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 Continue
through 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.com
orhttp://localhost:3000
) - Authorized redirect URIs: Add
https://your-domain.com/api/auth/callback/google
(orhttp://localhost:3000/api/auth/callback/google
for local development)
- 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"
- Ensure
website.tsx
fileauth.enableGoogleLogin
is 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.
4. Configure Credential Login
To enable credential login, follow these steps to obtain client credentials:
- Follow the requirements of Email Configuration document to configure email service
- Update
website.tsx
file, setenableCredentialLogin
totrue
, 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
Authentication System Structure
The authentication system in MkSaaS is designed with the following components:
Core Features
- Email and password authentication with email verification
- Social login, default support Google, GitHub login, you can extend more social providers, like Twitter, Apple, Facebook, etc.
- Account linking between different authentication methods, for example, link GitHub account to email account
- User and role management, including admin functionality, for example, ban user
- Automatic newsletter subscription on registration (configurable)
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>;
}
Best Practices
- Require Email Verification: Always require email verification for new users
- Provide Multiple Authentication Methods: Offer both email/password and social logins
- Use Secure Session Settings: Configure appropriate session timeouts and cookie security
- Protect Sensitive Routes: Implement proper authorization checks on both client and server
- Consider Different User Roles: Implement proper role-based access controls
Video Tutorial
Next Steps
Now that you understand how authentication works in MkSaaS, explore these related integrations: