middleware.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
  3. export async function middleware(request: NextRequest) {
  4. // Allow public routes
  5. const publicPaths = [
  6. "/",
  7. "/api/auth/login",
  8. "/api/auth/register",
  9. "/api/auth/callback",
  10. "/api/auth/logout",
  11. "/favicon.ico",
  12. "/_next",
  13. "/public",
  14. ];
  15. const pathname = request.nextUrl.pathname;
  16. const isPublicPath = publicPaths.some(path => pathname.startsWith(path));
  17. // Allow public access to auth routes and static assets
  18. if (isPublicPath) {
  19. return NextResponse.next();
  20. }
  21. // Check authentication for protected routes
  22. const protectedPaths = [
  23. "/files",
  24. "/api-docs",
  25. ];
  26. const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path));
  27. if (isProtectedPath) {
  28. try {
  29. const { isAuthenticated } = getKindeServerSession();
  30. const authenticated = await isAuthenticated();
  31. // Add debugging headers
  32. const response = NextResponse.next();
  33. response.headers.set('X-Auth-Status', authenticated ? 'authenticated' : 'unauthenticated');
  34. if (!authenticated) {
  35. // Redirect to login page if not authenticated
  36. const loginUrl = new URL("/api/auth/login", request.url);
  37. loginUrl.searchParams.set("post_login_redirect_url", pathname);
  38. return NextResponse.redirect(loginUrl);
  39. }
  40. return response;
  41. } catch (error) {
  42. console.error("Authentication check failed:", error);
  43. // Redirect to login on authentication error
  44. const loginUrl = new URL("/api/auth/login", request.url);
  45. return NextResponse.redirect(loginUrl);
  46. }
  47. }
  48. // Allow all other routes
  49. return NextResponse.next();
  50. }
  51. export const config = {
  52. matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
  53. };