Crash Courses · Basic
Authentication
Add email, OAuth, and magic link auth to your Next.js app with Supabase Auth.
11 min read+150 XP on completionCert: Supabase Crash Course
Tap any word in the text below to start reading from there.
Authentication
Supabase Auth manages users, sessions, OAuth, and JWT tokens. The @supabase/ssr package syncs sessions via cookies in Next.js.
Sign Up and Sign In
'use client'
import { createClient } from '@/lib/supabase/client'
const supabase = createClient()
// Sign up
async function signUp(email: string, password: string) {
const { data, error } = await supabase.auth.signUp({ email, password })
if (error) throw error
return data
}
// Sign in
async function signIn(email: string, password: string) {
const { data, error } = await supabase.auth.signInWithPassword({ email, password })
if (error) throw error
return data.session
}
// OAuth (Google)
async function signInWithGoogle() {
await supabase.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: `${window.location.origin}/auth/callback` },
})
}
// Sign out
async function signOut() {
await supabase.auth.signOut()
}Auth Callback Route
// app/auth/callback/route.ts
import { createServerClient } from '@supabase/ssr'
import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
export async function GET(req: NextRequest) {
const code = req.nextUrl.searchParams.get('code')
if (code) {
const cookieStore = await cookies()
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { getAll: () => cookieStore.getAll(), setAll: (c) => c.forEach(({name,value,options}) => cookieStore.set(name,value,options)) } }
)
await supabase.auth.exchangeCodeForSession(code)
}
return NextResponse.redirect(new URL('/dashboard', req.url))
}Get Current User (Server)
// In a server component
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
export default async function DashboardPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
return <Dashboard userId={user.id} />
}Reading progress
0% read
In this module
signUp
signInWithPassword
signInWithOAuth
getUser()
0%