2024-11-24 23:30:44 +05:00
|
|
|
import type { Session } from "better-auth/types";
|
|
|
|
import { type NextRequest, NextResponse } from "next/server";
|
|
|
|
|
|
|
|
export default async function authMiddleware(request: NextRequest) {
|
2025-01-11 05:31:13 +05:30
|
|
|
const protocol = request.headers.get("x-forwarded-proto") || "http";
|
|
|
|
const host = request.headers.get("host") || "localhost:3000";
|
|
|
|
|
|
|
|
try {
|
2025-01-15 10:35:03 +05:00
|
|
|
const response = await fetch(`${protocol}://${host}/api/auth/get-session`, {
|
|
|
|
method: "GET",
|
|
|
|
headers: {
|
|
|
|
cookie: request.headers.get("cookie") || "",
|
|
|
|
host: host,
|
2025-01-11 04:31:04 +05:30
|
|
|
},
|
2025-01-15 10:35:03 +05:00
|
|
|
next: { revalidate: 600 }, // Cache for 10 minutes (600 seconds)
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
throw new Error("Failed to fetch session");
|
|
|
|
}
|
|
|
|
|
|
|
|
const session: Session = await response.json();
|
2024-11-24 23:30:44 +05:00
|
|
|
|
2025-01-11 05:31:13 +05:30
|
|
|
if (!session) {
|
|
|
|
return NextResponse.redirect(new URL("/login", request.url));
|
|
|
|
}
|
|
|
|
return NextResponse.next();
|
|
|
|
} catch (error) {
|
2025-01-15 10:35:03 +05:00
|
|
|
console.log("Middleware error", error);
|
2025-01-11 04:31:04 +05:30
|
|
|
return NextResponse.redirect(new URL("/login", request.url));
|
|
|
|
}
|
2024-11-24 23:30:44 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
export const config = {
|
2024-12-13 11:24:13 +05:00
|
|
|
matcher: ["/devices", "/", "/payments", "/payments/:paymentId"],
|
2024-11-24 23:30:44 +05:00
|
|
|
};
|