Authentication

Complete authentication system with Better Auth

Installation

1

Install the Package

Add Authentication to your project using the Codelesskit CLI:

pnpm dlx codelesskit@latest add auth
2

Set Environment Variables

Create a `.env` file in the root of your project and add the following environment variables:

.env
1
2
3
4
5
6
7
8
9
10
11
12
# App Configuration
NEXT_PUBLIC_APP_URL="http://localhost:3000"
 
# Auth Configuration
BETTER_AUTH_URL="http://localhost:3000"
BETTER_AUTH_SECRET="your-secret-key-here-replace-with-secure-random-string"
# Generate a secure random string using: openssl rand -base64 32
 
# Google OAuth (Optional)
# Uncomment and fill these if you want to enable Google authentication
# GOOGLE_CLIENT_ID="your_google_client_id"
# GOOGLE_CLIENT_SECRET="your_google_client_secret"

Usage

Once you've installed Authentication, you can start using the following actions:

signInWithEmail

Sign in a user with email and password.

1
2
3
import { signInWithEmail } from '@/lib/auth/actions'
 
await signInWithEmail(email, password)

signUpWithEmail

Create a new user account with email and password.

1
2
3
import { signUpWithEmail } from '@/lib/auth/actions'
 
await signUpWithEmail(email, password, name)

signInWithGoogle

Sign in a user with Google OAuth.

1
2
3
import { signInWithGoogle } from '@/lib/auth/actions'
 
await signInWithGoogle()

signOutAction

Sign out the current user.

1
2
3
import { signOutAction } from '@/lib/auth/actions'
 
await signOutAction()

getSession

Get the current user session. Returns null if not authenticated.

1
2
3
4
5
6
import { getSession } from '@/lib/auth'
 
const session = await getSession()
if (session) {
console.log('User:', session.user)
}

updateUser

Update the current user's profile information.

1
2
3
import { updateUser } from '@/lib/auth/actions'
 
await updateUser({ name: 'New Name', image: 'https://...' })

forgotPassword

Send a password reset email to the user.

1
2
3
import { forgotPassword } from '@/lib/auth/actions'
 
await forgotPassword(email)

resetPassword

Reset the user's password using a reset token.

1
2
3
import { resetPassword } from '@/lib/auth/actions'
 
await resetPassword(token, newPassword)

useAuthActions

React hook for authentication operations in client components. Provides signIn, signUp, signOut, and other auth methods.

1
2
3
4
5
6
7
8
9
import { useAuthActions } from '@/lib/auth/hooks'
 
function LoginForm() {
const { signIn, isLoading, error } = useAuthActions()
const handleSubmit = async () => {
await signIn(email, password)
}
}

useAuth

React hook to access the current user session in client components.

1
2
3
4
5
6
import { useAuth } from '@/lib/auth/context'
 
function Profile() {
const { user, session } = useAuth()
return <div>Welcome {user?.name}</div>
}
Authentication | Codelesskit