-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
92 lines (81 loc) · 2.76 KB
/
Copy pathmiddleware.ts
File metadata and controls
92 lines (81 loc) · 2.76 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { createServerClient } from '@supabase/ssr'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// Routes that don't require authentication
const publicRoutes = ['/login', '/signup']
export async function middleware(req: NextRequest) {
console.log('[Middleware] Path:', req.nextUrl.pathname)
// Skip middleware if Supabase is not configured
if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) {
console.log('[Middleware] Supabase not configured, skipping')
return NextResponse.next()
}
let res = NextResponse.next({
request: {
headers: req.headers,
},
})
try {
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
{
cookies: {
getAll() {
return req.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => req.cookies.set(name, value))
res = NextResponse.next({
request: {
headers: req.headers,
},
})
cookiesToSet.forEach(({ name, value, options }) =>
res.cookies.set(name, value, options)
)
},
},
}
)
console.log('[Middleware] Getting session...')
const {
data: { session },
} = await supabase.auth.getSession()
console.log('[Middleware] Session:', session ? 'found' : 'none')
const isPublicRoute = publicRoutes.some(route => req.nextUrl.pathname.startsWith(route))
console.log('[Middleware] Is public route:', isPublicRoute)
// If user is not authenticated and trying to access a protected route
if (!session && !isPublicRoute) {
const redirectUrl = new URL('/login', req.url)
return NextResponse.redirect(redirectUrl)
}
// If user is authenticated and trying to access login/signup
if (session && isPublicRoute) {
const redirectUrl = new URL('/', req.url)
return NextResponse.redirect(redirectUrl)
}
return res
} catch (error) {
console.error('Middleware auth error:', error)
// On error, allow access to public routes, redirect others to login
const isPublicRoute = publicRoutes.some(route => req.nextUrl.pathname.startsWith(route))
if (!isPublicRoute) {
return NextResponse.redirect(new URL('/login', req.url))
}
return NextResponse.next()
}
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
* - api routes
*/
'/((?!_next/static|_next/image|favicon.ico|public|api).*)',
],
}