Files
ember-market-frontend/middleware.ts
NotII e3e630c211 fix
2025-03-23 22:14:05 +00:00

50 lines
1.6 KiB
TypeScript

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const token = req.cookies.get("Authorization")?.value;
if (!token) {
console.log("Middleware: No token found, redirecting to login...");
return NextResponse.redirect(new URL("/auth/login", req.url));
}
console.log("Middleware: Token found, validating...");
try {
// Use our internal API route that handles the auth check server-side
// This avoids SSL issues as it's a same-origin request
const origin = req.nextUrl.origin;
const authCheckUrl = `${origin}/api/auth/check`;
console.log(`Middleware: Using internal auth check URL: ${authCheckUrl}`);
const res = await fetch(authCheckUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
// Explicitly pass the token in headers as well
"Authorization": `Bearer ${token}`
},
credentials: 'include',
});
console.log(`Middleware: Auth check responded with status ${res.status}`);
if (!res.ok) {
console.log(`Middleware: Auth check failed with status ${res.status}, redirecting to login`);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
console.log("Middleware: Auth check successful, proceeding to dashboard");
} catch (error) {
console.error("Middleware: Authentication validation failed:", error);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};