-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
57 lines (48 loc) · 2.04 KB
/
middleware.ts
File metadata and controls
57 lines (48 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(req: NextRequest) {
const res = NextResponse.next()
const supabase = createMiddlewareClient({ req, res })
const {
data: { session },
} = await supabase.auth.getSession()
// Protect dashboard routes
// Allow if "code" search param is present, to let Supabase client handle the OAuth exchange on the dashboard page
if (req.nextUrl.pathname.startsWith('/dashboard') && !req.nextUrl.searchParams.has('code')) {
if (!session) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/login'
// Preserve the original path and ALL existing search params (like ?welcome=true)
redirectUrl.searchParams.set('redirect', req.nextUrl.pathname + req.nextUrl.search)
return NextResponse.redirect(redirectUrl)
}
}
// Redirect signed-in users away from login/signup pages
if (['/login', '/signup'].includes(req.nextUrl.pathname)) {
if (session) {
// Check if user has a username
const { data: profile } = await supabase
.from('profiles')
.select('username')
.eq('id', session.user.id)
.single()
const redirectUrl = req.nextUrl.clone()
// If no username, send to claim page
if (!profile?.username) {
redirectUrl.pathname = '/claim'
} else {
redirectUrl.pathname = '/dashboard'
// Preserve query params when force-redirecting to dashboard
req.nextUrl.searchParams.forEach((value, key) => {
redirectUrl.searchParams.set(key, value)
})
}
return NextResponse.redirect(redirectUrl)
}
}
return res
}
export const config = {
matcher: ['/dashboard/:path*', '/claim', '/login', '/signup'],
}