Bootstrap React app with Supabase Auth
Provides copy-paste TypeScript code for Supabase Auth in React: client setup, AuthProvider, and ProtectedRoute.
What this file does
Provides copy-paste TypeScript code for Supabase Auth in React: client setup, AuthProvider, and ProtectedRoute.
When to use it
- Starting a new React project that needs Supabase authentication
- Adding auth to an existing React app with Supabase backend
- Implementing protected routes with React Router and Supabase
- Setting up session persistence and auth state listeners
Assumes this stack
title: "Bootstrap React app with Supabase Auth" description: "Guidelines for writing React apps with Supabase Auth" tags: ["React", "Supabase", "Authentication", "Setup", "Frontend"] category: "Coding" author: "Csaba Farkas" slug: "bootstrap-react-app-with-supabase-auth" id: "coding-143" seo_keywords: "React Supabase integration, Supabase setup, React authentication, AuthProvider, Protected routes" date: "2025-07-13" difficulty: "Advanced" schema_type: "TechArticle"
Bootstrap React app with Supabase Auth
Guidelines for writing React apps with Supabase Auth
Overview of implementing Supabase Auth
- Install required dependencies
- Set up environment variables
- Create Supabase client
- Implement authentication components
- Set up protected routes
๐จ CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS ๐จ
As an AI language model, you MUST follow these guidelines when implementing Supabase Auth in React:
- Always use the latest version of @supabase/supabase-js
- Implement proper error handling for authentication operations
- Use environment variables for Supabase credentials
- Implement proper session management
- Handle authentication state changes correctly
CORRECT CLIENT IMPLEMENTATION
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
}
})
CORRECT AUTH PROVIDER IMPLEMENTATION
import { createContext, useContext, useEffect, useState } from 'react'
import { User } from '@supabase/supabase-js'
import { supabase } from './supabaseClient'
const AuthContext = createContext<{
user: User | null
loading: boolean
}>({
user: null,
loading: true
})
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
// Check active sessions and sets the user
supabase.auth.getSession().then(({ data: { session } }) => {
setUser(session?.user ?? null)
setLoading(false)
})
// Listen for changes on auth state (logged in, signed out, etc.)
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null)
setLoading(false)
})
return () => subscription.unsubscribe()
}, [])
return (
<AuthContext.Provider value={{ user, loading }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
return useContext(AuthContext)
}
CORRECT PROTECTED ROUTE IMPLEMENTATION
import { Navigate } from 'react-router-dom'
import { useAuth } from './AuthProvider'
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth()
if (loading) {
return <div>Loading...</div>
}
if (!user) {
return <Navigate to="/login" />
}
return <>{children}</>
}
AI MODEL VERIFICATION STEPS
Before generating any code, you MUST verify:
- Are you using the latest version of @supabase/supabase-js?
- Have you implemented proper error handling?
- Are you using environment variables for credentials?
- Is session management properly implemented?
- Are authentication state changes being handled?
CONSEQUENCES OF INCORRECT IMPLEMENTATION
If you generate code without following these guidelines:
- Authentication state may become inconsistent
- Sessions may not persist correctly
- Security vulnerabilities may be introduced
- Users may experience authentication loops
- Token refresh may fail
AI MODEL RESPONSE TEMPLATE
When implementing Supabase Auth in React, you MUST:
- Follow the patterns shown in this guide
- Implement proper error handling
- Use the AuthProvider for state management
- Protect sensitive routes
- Handle authentication state changes
What's inside
3 code blocks (client, provider, protected route) plus verification steps and response template
Change this for your project
- Replace
VITE_SUPABASE_URLandVITE_SUPABASE_ANON_KEYwith your own Supabase project credentials - Replace
/logininProtectedRoutewith your actual login route path
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Auth state managed via React Context with a single
useAuthhook - Session subscription cleaned up on unmount to prevent memory leaks
Related Documents
How you work
Defines personality, planning, task execution, and communication conventions for a coding agent in the Codex CLI environment.
ๅ ็ฝฎ Agent ๆ็คบ่ฏ
Documents the system prompts, tool permissions, and model assignments for six built-in subagents in Claude Code.
System Prompt โ Voice Interview Agent
Defines a voice agent named Carol that conducts structured five-question interviews about gender topics for a magazine article.
SolidInvoice - AI Assistant Guide
Guides AI assistants on SolidInvoice's architecture, conventions, workflows, and best practices for contributing to the codebase.