The AuthStore manages user authentication state, including session management and login/logout operations. Supports OAuth providers and magic link authentication via Supabase.
Import
import { useAuthStore } from "../stores/AuthStore"
Usage
const Login = () => {
const { loading, loginWithSocial, loginWithOtp } = useAuthStore(state => ({
loading: state.loading,
loginWithSocial: state.loginWithSocial,
loginWithOtp: state.loginWithOtp
}))
const handleGitHubLogin = () => {
loginWithSocial('github')
}
const handleEmailLogin = (email: string) => {
loginWithOtp(email)
}
return (
<div>
<button onClick={handleGitHubLogin} disabled={loading}>
Continue with GitHub
</button>
<button onClick={() => handleEmailLogin('[email protected]')} disabled={loading}>
Send Magic Link
</button>
</div>
)
}
const App = () => {
const { session, setSession } = useAuthStore(state => ({
session: state.session,
setSession: state.setSession
}))
useEffect(() => {
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session)
})
}, [])
return (
<main>
{session ? <Bookmarks /> : <Showcase />}
</main>
)
}
State Properties
session
Session | null
default:"null"
The current Supabase authentication session. Contains user data, access tokens, and session metadata. null when user is not authenticated.
Loading state for authentication operations (login, logout).
Methods
setSession
Manually sets the authentication session. Typically used with Supabase’s auth state change listener.
The Supabase session object, or null to clear the session.
const setSession = useAuthStore(state => state.setSession)
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session)
})
loginWithSocial
Initiates OAuth login with a social provider.
The OAuth provider to use. Supabase supports providers like 'github', 'google', 'gitlab', etc.
Returns: Promise<void>
const loginWithSocial = useAuthStore(state => state.loginWithSocial)
const handleLogin = async () => {
await loginWithSocial('github')
// User will be redirected to GitHub for authentication
// Then redirected back to window.location.origin
}
loginWithOtp
Sends a magic link to the user’s email for passwordless authentication.
The email address to send the magic link to.
Returns: Promise<void>
const loginWithOtp = useAuthStore(state => state.loginWithOtp)
const handleEmailLogin = async (email: string) => {
await loginWithOtp(email)
showSuccessToast(`Please check your email! We've sent the login link to ${email}.`)
}
logout
Signs out the current user and clears the session.
Returns: Promise<void>
const Header = () => {
const { session, logout } = useAuthStore(state => ({
session: state.session,
logout: state.logout
}))
const handleLogout = async () => {
await logout()
// Session is now null
}
return (
<header>
{session && (
<button onClick={handleLogout}>
Sign out
</button>
)}
</header>
)
}
Type Definitions
import { Session, Provider } from "@supabase/supabase-js"
type AuthState = {
session: Session | null
setSession: (session: Session | null) => void
loading: boolean
loginWithSocial: (provider: Provider) => Promise<void>
loginWithOtp: (email: string) => Promise<void>
logout: () => Promise<void>
}
Session Object
The Supabase Session object contains:
user - User object with id, email, user_metadata, etc.
access_token - JWT access token for authenticated requests
refresh_token - Token for refreshing the session
expires_at - Session expiration timestamp
const session = useAuthStore(state => state.session)
if (session) {
const userId = session.user.id
const userEmail = session.user.email
const userName = session.user.user_metadata.name
}
Implementation Details
- State Management: Uses Zustand for reactive authentication state
- OAuth Redirect: Social login redirects users back to
window.location.origin
- Session Persistence: Supabase automatically persists sessions in localStorage
- Error Handling: Errors are logged to console; implement custom error handling as needed
- Auth State Sync: Use
supabase.auth.onAuthStateChange() with setSession() to keep the store in sync
- Loading States: The
loading flag is set during all authentication operations for UI feedback
Common Patterns
Protected Routes
const App = () => {
const session = useAuthStore(state => state.session)
return session ? <AuthenticatedApp /> : <LandingPage />
}
Accessing User Data
const Profile = () => {
const session = useAuthStore(state => state.session)
const userId = session?.user.id
useEffect(() => {
if (userId) {
// Fetch user-specific data
}
}, [userId])
}
Conditional Rendering
const Header = () => {
const { session, logout } = useAuthStore(state => ({
session: state.session,
logout: state.logout
}))
return (
<header>
{session ? (
<button onClick={logout}>Sign out</button>
) : (
<LoginButton>Sign in</LoginButton>
)}
</header>
)
}