Files
ember-market-frontend/middleware.ts
2025-03-10 17:39:37 +00:00

45 lines
1.4 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("No token found, redirecting to login...");
return NextResponse.redirect(new URL("/auth/login", req.url));
}
try {
// Make sure we use a complete URL with protocol
// When running locally with integrated backend, we need to specify the full URL including protocol
const origin = req.nextUrl.origin;
const authEndpoint = new URL("/api/auth/me", origin).toString();
console.log("Verifying authentication with endpoint:", authEndpoint);
const res = await fetch(authEndpoint, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
// Ensure we're not caching authentication checks
cache: 'no-store'
});
if (!res.ok) {
console.error(`Auth check failed with status: ${res.status}`);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
} catch (error) {
console.error("Authentication validation failed:", error);
console.error("Error details:", error instanceof Error ? error.message : 'Unknown error');
return NextResponse.redirect(new URL("/auth/login", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};