-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
55 lines (47 loc) · 1.62 KB
/
middleware.ts
File metadata and controls
55 lines (47 loc) · 1.62 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
import { auth } from '@/lib/auth';
import { NextResponse } from 'next/server';
const ANONYMOUS_COOKIE = 'loggerai-anonymous-session';
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isAnonymous = req.cookies.get(ANONYMOUS_COOKIE)?.value === 'true';
// Public routes that don't require authentication
const publicRoutes = ['/login', '/api/auth'];
const isPublicRoute = publicRoutes.some(route =>
nextUrl.pathname.startsWith(route)
);
// Allow public routes
if (isPublicRoute) {
// Redirect to home if already logged in and trying to access login
if ((isLoggedIn || isAnonymous) && nextUrl.pathname === '/login') {
return NextResponse.redirect(new URL('/', nextUrl));
}
return NextResponse.next();
}
// Allow anonymous users to access the app
if (isAnonymous) {
// Add header to identify anonymous requests for API routes
const response = NextResponse.next();
response.headers.set('x-anonymous-mode', 'true');
return response;
}
// Redirect to login if not authenticated
if (!isLoggedIn) {
const loginUrl = new URL('/login', nextUrl);
loginUrl.searchParams.set('callbackUrl', nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
});
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public files (public folder)
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};