-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
48 lines (39 loc) · 1.24 KB
/
middleware.ts
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
import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(req: NextRequest) {
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const { pathname } = req.nextUrl;
// Define protected routes
const protectedRoutes = [
'/dashboard',
'/browse',
'/create-room',
'/your-rooms',
'/rooms',
'/edit-room',
'/signout'
];
// Redirect to dashboard if user is logged in and tries to access the home page
if (pathname === '/' && token) {
return NextResponse.redirect(new URL('/dashboard', req.url));
}
// Redirect to home if user is not authenticated and tries to access a protected route
if (!token && (protectedRoutes.some(route => pathname.startsWith(route)) || pathname.startsWith('/rooms/'))) {
return NextResponse.redirect(new URL('/', req.url));
}
// Allow request to proceed
return NextResponse.next();
}
export const config = {
matcher: [
'/',
'/dashboard',
'/browse',
'/create-room/:path*',
'/your-rooms/:path*',
'/rooms/:path*',
'/edit-room/:path*',
'/signout/:path*',
],
};