Supabase with React

Add a database and magic link auth to a React app with Supabase.

When building a side project in React you'll often need a database and user accounts, but you don't want to build and host a whole backend for it. Supabase gives you a Postgres database, auth and an API you can call straight from the browser with @supabase/supabase-js.

Let's build a small todo app with Vite, React and version 2 of supabase-js.

Step 1: Create the React app and Supabase client

Create a new Vite app with the React template and install supabase-js:

npm create vite@latest supabase-todos -- --template react
cd supabase-todos
npm install @supabase/supabase-js

Create a new project in the Supabase dashboard, then grab the Project URL and the anon public key from Project Settings → API. Add them to a .env.local file:

# .env.local
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key

Vite only exposes environment variables that start with VITE_ to your app. Now create a client we can import anywhere:

// src/supabaseClient.js
import { createClient } from "@supabase/supabase-js"
export const supabase = createClient(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_ANON_KEY
)

Step 2: Create a todos table with Row Level Security

In the dashboard, open the SQL Editor and run this:

create table todos (
id bigint generated by default as identity primary key,
user_id uuid references auth.users not null default auth.uid(),
title text not null,
is_complete boolean default false,
created_at timestamp with time zone default now()
);
alter table todos enable row level security;
create policy "Users can manage their own todos"
on todos for all
using (auth.uid() = user_id)
with check (auth.uid() = user_id);

The user_id column defaults to auth.uid(), the ID of the signed in user, so we never have to send it from React. The policy makes sure each user can only read and change their own rows.

Important! The anon key ends up in your JavaScript bundle, so anyone can see it. That's fine only because Row Level Security is on. Without it, anyone with your anon key could read and write every row in the table.

You can also create the table in the Table Editor. Just leave "Enable Row Level Security" checked and add the policy under Authentication → Policies.

Step 3: Sign in with a magic link

With RLS on, nothing comes back until a user is signed in, so let's start with auth. Supabase can email a magic link, so there's no password to manage:

// src/Auth.jsx
import { useState } from "react"
import { supabase } from "./supabaseClient"
export default function Auth() {
const [email, setEmail] = useState("")
const [sent, setSent] = useState(false)
const handleSubmit = async (e) => {
e.preventDefault()
const { error } = await supabase.auth.signInWithOtp({ email })
if (error) {
alert(error.message)
} else {
setSent(true)
}
}
if (sent) return <p>Check your email for the login link.</p>
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Send magic link</button>
</form>
)
}

The link redirects back to your Site URL, so set it to http://localhost:5173 under Authentication → URL Configuration while you're developing. If you'd rather use passwords, signUp({ email, password }) and signInWithPassword({ email, password }) work the same way.

Now we need to know when someone is signed in. getSession gives us the current session on load, and onAuthStateChange fires when the user signs in or out:

// src/App.jsx
import { useEffect, useState } from "react"
import { supabase } from "./supabaseClient"
import Auth from "./Auth"
import Todos from "./Todos"
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()
}, [])
return session ? <Todos /> : <Auth />
}

In v2 onAuthStateChange returns { data: { subscription } }. Unsubscribing in the cleanup function stops the listener from piling up when the component unmounts (or runs twice in React's Strict Mode).

Step 4: Read, insert, update and delete todos

Queries are chained off supabase.from("todos") and return { data, error }:

// src/Todos.jsx
import { useEffect, useState } from "react"
import { supabase } from "./supabaseClient"
export default function Todos() {
const [todos, setTodos] = useState([])
const [title, setTitle] = useState("")
useEffect(() => {
const getTodos = async () => {
const { data, error } = await supabase
.from("todos")
.select()
.order("created_at")
if (!error) setTodos(data)
}
getTodos()
}, [])
const addTodo = async (e) => {
e.preventDefault()
const { data, error } = await supabase
.from("todos")
.insert({ title })
.select()
if (!error) {
setTodos([...todos, ...data])
setTitle("")
}
}
const toggleTodo = async (todo) => {
const { error } = await supabase
.from("todos")
.update({ is_complete: !todo.is_complete })
.eq("id", todo.id)
if (!error) {
setTodos(
todos.map((t) =>
t.id === todo.id ? { ...t, is_complete: !t.is_complete } : t
)
)
}
}
const deleteTodo = async (id) => {
const { error } = await supabase.from("todos").delete().eq("id", id)
if (!error) setTodos(todos.filter((t) => t.id !== id))
}
return (
<div>
<form onSubmit={addTodo}>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.is_complete}
onChange={() => toggleTodo(todo)}
/>
{todo.title}
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
<button onClick={() => supabase.auth.signOut()}>Sign out</button>
</div>
)
}

A few things to know about these queries:

  • .select() with no arguments returns every column.
  • In v2, .insert() doesn't return the new row by default. Chaining .select() on the end gives you the row back, including the id Postgres generated.
  • .update() and .delete() need a filter like .eq("id", todo.id), or they'd try to change every row the user can see.
  • Thanks to the policy we never filter by user. Supabase only returns the signed in user's todos.

Run npm run dev, open localhost:5173, sign in with your email and add a few todos. You'll see them show up in the Table Editor in the dashboard.

Signing out is just as easy. supabase.auth.signOut() clears the session, onAuthStateChange fires and the app shows the sign in form again.

Have some feedback on this post? .