Files
ember-market-frontend/middleware.ts
2025-03-23 21:58:38 +00:00

39 lines
1.2 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 {
// Use SERVER_API_URL which should be set to a working URL in the .env files
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
console.log(`Using API URL for authentication: ${apiUrl}/auth/me`);
const res = await fetch(`${apiUrl}/auth/me`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
// No Node.js-specific options as middleware runs in Edge Runtime
});
if (!res.ok) {
return NextResponse.redirect(new URL("/auth/login", req.url));
}
} catch (error) {
console.error("Authentication validation failed:", error);
return NextResponse.redirect(new URL("/auth/login", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};