-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathmiddleware.js
More file actions
37 lines (31 loc) 路 991 Bytes
/
Copy pathmiddleware.js
File metadata and controls
37 lines (31 loc) 路 991 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 { NextResponse } from 'next/server';
const SESSION_COOKIE_NAMES = [
'better-auth.session_token',
'__Secure-better-auth.session_token',
'__Host-better-auth.session_token',
];
export default async function middleware(req) {
// Get the pathname of the request (e.g. /, /admin)
const path = req.nextUrl.pathname;
// A list of all protected pages
const protectedPaths = [
'/admin',
'/admin/customize',
'/admin/analytics',
'/admin/settings',
'/onboarding',
];
// If it's the root path, just render it
if (path === '/') {
return NextResponse.next();
}
const session = SESSION_COOKIE_NAMES.find(
(cookieName) => req.cookies.get(cookieName)?.value
);
if (!session && protectedPaths.includes(path)) {
return NextResponse.redirect(new URL('/login', req.url));
} else if (session && (path === '/login' || path === '/register')) {
return NextResponse.redirect(new URL('/admin', req.url));
}
return NextResponse.next();
}