-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
62 lines (48 loc) · 1.79 KB
/
Copy pathmiddleware.ts
File metadata and controls
62 lines (48 loc) · 1.79 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
import { NextResponse, type NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isApiRoute = pathname.startsWith('/api/');
if (isApiRoute) return NextResponse.next();
const isPublicRoute =
pathname.startsWith('/terms') ||
pathname.startsWith('/privacy');
if (isPublicRoute) return NextResponse.next();
const isAuthRoute =
pathname.startsWith('/login') ||
pathname.startsWith('/register') ||
pathname.startsWith('/check-email') ||
pathname.startsWith('/forgot-password') ||
pathname.startsWith('/reset-password') ||
pathname.startsWith('/auth/callback');
const isPWARoute =
pathname.startsWith('/serwist') ||
pathname.startsWith('/~offline') ||
pathname === '/manifest.json';
if (isPWARoute) return NextResponse.next();
const isAppRoute =
!isAuthRoute &&
!pathname.startsWith('/_next') &&
!pathname.startsWith('/favicon') &&
pathname !== '/';
// Supabase stores the session in a cookie named sb-*-auth-token
const hasSession = request.cookies.getAll().some((c) => c.name.includes('-auth-token'));
if (isAppRoute && !hasSession) {
const url = request.nextUrl.clone();
url.pathname = '/login';
return NextResponse.redirect(url);
}
const skipRedirectWhenAuthenticated =
pathname.startsWith('/reset-password') ||
pathname.startsWith('/auth/callback');
if (isAuthRoute && hasSession && !skipRedirectWhenAuthenticated) {
const url = request.nextUrl.clone();
url.pathname = '/dashboard';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|icons/|sw\\.js|swe-worker|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};