-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
58 lines (50 loc) · 1.53 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
49
50
51
52
53
54
55
56
57
58
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export function middleware(req: NextRequest) {
// Get the pathname
const { pathname } = req.nextUrl;
// Skip Auth0 routes - let Auth0 handle these
if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
// Simple check for authentication via cookie
const authCookie = req.cookies.get("appSession");
// Protected API routes
if (pathname.startsWith("/api/chat")) {
// If no auth cookie is present, return 401
if (!authCookie) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
}
// For authenticated requests, continue
return NextResponse.next();
}
// Protected pages (chatbot and protected)
if (
pathname === "/chatbot" ||
pathname.startsWith("/chatbot/") ||
pathname === "/protected"
) {
// If no auth cookie is present, redirect to login
if (!authCookie) {
// Need to encode the return URL
const returnTo = encodeURIComponent(pathname);
return NextResponse.redirect(
new URL(`/api/auth/login?returnTo=${returnTo}`, req.url)
);
}
}
// Allow all other routes
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
"/((?!_next/static|_next/image|favicon.ico|public).*)",
],
};