Authentication
Complete authentication system with Better Auth
Installation
Install the Package
Add Authentication to your project using the Codelesskit CLI:
Set Environment Variables
Create a `.env` file in the root of your project and add the following environment variables:
123456789101112# App ConfigurationNEXT_PUBLIC_APP_URL="http://localhost:3000" # Auth ConfigurationBETTER_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.
123import { signInWithEmail } from '@/lib/auth/actions' await signInWithEmail(email, password)signUpWithEmail
Create a new user account with email and password.
123import { signUpWithEmail } from '@/lib/auth/actions' await signUpWithEmail(email, password, name)signInWithGoogle
Sign in a user with Google OAuth.
123import { signInWithGoogle } from '@/lib/auth/actions' await signInWithGoogle()signOutAction
Sign out the current user.
123import { signOutAction } from '@/lib/auth/actions' await signOutAction()getSession
Get the current user session. Returns null if not authenticated.
123456import { getSession } from '@/lib/auth' const session = await getSession()if (session) { console.log('User:', session.user)}updateUser
Update the current user's profile information.
123import { updateUser } from '@/lib/auth/actions' await updateUser({ name: 'New Name', image: 'https://...' })forgotPassword
Send a password reset email to the user.
123import { forgotPassword } from '@/lib/auth/actions' await forgotPassword(email)resetPassword
Reset the user's password using a reset token.
123import { 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.
123456789import { 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.
123456import { useAuth } from '@/lib/auth/context' function Profile() { const { user, session } = useAuth() return <div>Welcome {user?.name}</div>}