-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
74 lines (64 loc) · 1.99 KB
/
middleware.ts
File metadata and controls
74 lines (64 loc) · 1.99 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// Routes that don't require authentication
const publicRoutes = [
'/',
'/auth',
'/auth/login',
'/auth/signup',
'/auth/forgot-password',
'/auth/confirm',
'/verify',
'/leaderboard',
'/pricing',
'/community',
]
// API routes that don't require authentication
const publicApiRoutes = [
'/api/auth',
'/api/community',
'/api/leaderboard',
'/api/certifications',
]
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// Allow public routes
if (publicRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`))) {
return NextResponse.next()
}
// Allow public API routes
if (publicApiRoutes.some(route => pathname.startsWith(route))) {
return NextResponse.next()
}
// For all other routes, check authentication
try {
const supabase = createMiddlewareClient({ req: request, res: NextResponse.next() })
const { data: { session }, error } = await supabase.auth.getSession()
// If no session or error, redirect to login
if (!session || error) {
const loginUrl = new URL('/auth/login', request.url)
loginUrl.searchParams.set('redirect', pathname)
return NextResponse.redirect(loginUrl)
}
return NextResponse.next()
} catch (error) {
// On error, redirect to login
const loginUrl = new URL('/auth/login', request.url)
loginUrl.searchParams.set('redirect', pathname)
return NextResponse.redirect(loginUrl)
}
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder files
* - api/auth routes (auth endpoints)
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}