forked from sillysachin/scira
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (33 loc) · 1.34 KB
/
middleware.ts
File metadata and controls
42 lines (33 loc) · 1.34 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
import { NextRequest, NextResponse } from 'next/server';
import { getSessionCookie } from 'better-auth/cookies';
const authRoutes = ['/sign-in', '/sign-up'];
const protectedRoutes = ['/settings'];
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request);
const { pathname } = request.nextUrl;
console.log('Pathname: ', pathname);
// /api/payments/webhooks is a webhook endpoint that should be accessible without authentication
if (pathname.startsWith('/api/payments/webhooks')) {
return NextResponse.next();
}
if (pathname.startsWith('/polar/webhooks')) {
return NextResponse.next();
}
// If user is authenticated but trying to access auth routes
if (sessionCookie && authRoutes.some((route) => pathname.startsWith(route))) {
console.log('Redirecting to home');
console.log('Session cookie: ', sessionCookie);
return NextResponse.redirect(new URL('/', request.url));
}
if (!sessionCookie && protectedRoutes.some((route) => pathname.startsWith(route))) {
return NextResponse.redirect(new URL('/sign-in', request.url));
}
return NextResponse.next();
}
export const config = {
runtime: 'nodejs',
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
};