Use Supabase Auth with React
Learn how to use Supabase Auth with React.js.
Create a new Supabase project
Launch a new project in the Supabase Dashboard.
Your new database has a table for storing your users. You can see that this table is currently empty by running some SQL in the SQL Editor.
SQL_EDITOR
1select * from auth.users;
Create a React app
Create a React app using Vite.
Terminal
1npm create vite@latest my-app -- --template react
Install the Supabase client library
The fastest way to get started is to use Supabase's auth-ui-react
library which provides a convenient interface for working with Supabase Auth from a React app.
Navigate to the React app and install the Supabase libraries.
Terminal
1cd my-app && npm install @supabase/supabase-js @supabase/auth-ui-react @supabase/auth-ui-shared
Set up your login component
In App.jsx
, create a Supabase client using your Project URL and key.
Changes to API keys
Supabase is changing the way keys work to improve project security and developer experience. You can read the full announcement, but in the transition period, you can use both the current anon
and service_role
keys and the new publishable key with the form sb_publishable_xxx
which will replace the older keys.
To get the key values, open the API Keys section of a project's Settings page and do the following:
- For legacy keys, copy the
anon
key for client-side operations and theservice_role
key for server-side operations from the Legacy API Keys tab. - For new keys, open the API Keys tab, if you don't have a publishable key already, click Create new API Keys, and copy the value from the Publishable key section.
You can configure the Auth component to display whenever there is no session inside supabase.auth.getSession()
src/App.jsx
1234567891011121314151617181920212223242526272829303132import './index.css' import { useState, useEffect } from 'react' import { createClient } from '@supabase/supabase-js' import { Auth } from '@supabase/auth-ui-react' import { ThemeSupa } from '@supabase/auth-ui-shared' const supabase = createClient('https://<project>.supabase.co', '<sb_publishable_... or anon key>') export default function App() { const [session, setSession] = useState(null) useEffect(() => { supabase.auth.getSession().then(({ data: { session } }) => { setSession(session) }) const { data: { subscription }, } = supabase.auth.onAuthStateChange((_event, session) => { setSession(session) }) return () => subscription.unsubscribe() }, []) if (!session) { return (<Auth supabaseClient={supabase} appearance={{ theme: ThemeSupa }} />) } else { return (<div>Logged in!</div>) } }
Start the app
Start the app, go to http://localhost:3000 in a browser, and open the browser console and you should be able to log in.
Terminal
1npm run dev