-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
37 lines (30 loc) · 975 Bytes
/
middleware.ts
File metadata and controls
37 lines (30 loc) · 975 Bytes
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
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '~/lib/auth'
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// Check if the request is for the dashboard
if (pathname.startsWith('/dashboard')) {
const session = await auth.api.getSession({
headers: request.headers,
})
// If no session, redirect to login
if (!session) {
const loginUrl = new URL('/', request.url)
loginUrl.searchParams.set('redirect', pathname)
return NextResponse.redirect(loginUrl)
}
}
// If user is authenticated and on the root page, redirect to dashboard
if (pathname === '/') {
const session = await auth.api.getSession({
headers: request.headers,
})
if (session?.user) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
}
return NextResponse.next()
}
export const config = {
matcher: ['/', '/dashboard/:path*']
}