basics
-
“open source Firebase”
- why do ppl say this tho when supabase is sql and firebase is nosql LOL
-
provides fully managed postgresSQL database - backend-as-a-service
quickstart (with Next.js project)
- create - https://supabase.com/docs/guides/getting-started/quickstarts/nextjs
- auth - https://supabase.com/docs/guides/auth
setting up auth
-
ssr auth - app router recommended
-
to access supabase from app, need
- Client Component client (run in browser)
- Server Component client (route handlers, things that run only on server)
- cookies object tells Supabase client how to access cookies to read/write user session data
- Next.js throws an error if cookies are set from Server components → set up middleware to write cookies to storage
sb-<project_ref>-auth-token
-
Middleware
- refreshes expired auth tokens
supabase.auth.getUser
- passes auth token to server components since they can’t do it themselves
request.cookies.set
- pass token to browser to replace old token
response.cookies.set
- passes auth token to server components since they can’t do it themselves
- has matcher so middleware doesn’t run on non-supabase routes
- security note
- cookies can be spoofed
- always use supabase.auth.getUser to protect pages and user data
- never trust getSession inside server code like middleware - not guaranteed to revalidate Auth token
- safe to trust getUser because it always sends request to auth server to revalidate
- refreshes expired auth tokens
import { redirect } from 'next/navigation'
import { createClient } from '@/utils/supabase/server'
export default async function PrivatePage() {
const supabase = await createClient()
const { data, error } = await supabase.auth.getUser()
if (error || !data?.user) {
redirect('/login')
}
return <p>Hello {data.user.email}</p>
}
- create login page - use Server Action
understanding starter auth sign-up/sign-in
- all related pages under app/(auth-pages)
- basic form details → submit button with formAction pre-defined in
actions.ts
- gets formData, creates server client, error checks input, returns encodedRedirect with route + message to be added as query parameter that the original page has a handler for to display it (error or success message within searchParams)
- on successful sign-in, returns redirect to /protected page (under protected folder)
- encodedRedirect vs. redirect?
email verification on signup
- dashboard → emails - update email + redirect url
handling users
- Supabase auth automatically creates auth.users table
- if you want extra user details, make a separate profile table linked to auth.user
querying data
import { createClient } from '@/utils/supabase/server'
export default async function Page() {
const supabase = await createClient()
const { data: notes } = await supabase.from('notes').select()
return <pre>{JSON.stringify(notes, null, 2)}</pre>
}
-
with row-level security, need to add policies to tables allow authenticated users to read