-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
51 lines (42 loc) · 1.31 KB
/
Copy pathmiddleware.js
File metadata and controls
51 lines (42 loc) · 1.31 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
import { createServerClient } from '@supabase/ssr'
import { NextResponse } from 'next/server'
function getSupabaseConfig() {
return {
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
anonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,
}
}
export async function middleware(request) {
const { url, anonKey } = getSupabaseConfig()
let response = NextResponse.next({ request })
if (!url || !anonKey) {
return response
}
const supabase = createServerClient(url, anonKey, {
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value, options }) => {
request.cookies.set(name, value)
response.cookies.set(name, value, options)
})
},
},
})
const {
data: { user },
} = await supabase.auth.getUser()
const pathname = request.nextUrl.pathname
const isProtected = pathname.startsWith('/student/dashboard') || pathname.startsWith('/admin/dashboard')
if (isProtected && !user) {
const loginUrl = new URL('/login', request.url)
loginUrl.searchParams.set('next', pathname)
return NextResponse.redirect(loginUrl)
}
return response
}
export const config = {
matcher: ['/student/:path*', '/admin/:path*'],
}