import type { Session } from "better-auth/types"; import { type NextRequest, NextResponse } from "next/server"; export default async function authMiddleware(request: NextRequest) { const protocol = request.headers.get("x-forwarded-proto") || "http"; const host = request.headers.get("host") || "localhost:3000"; try { const response = await fetch(`${protocol}://${host}/api/auth/get-session`, { method: "GET", headers: { cookie: request.headers.get("cookie") || "", host: host, }, 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(); if (!session) { return NextResponse.redirect(new URL("/login", request.url)); } return NextResponse.next(); } catch (error) { console.log("Middleware error", error); return NextResponse.redirect(new URL("/login", request.url)); } } export const config = { matcher: ["/devices", "/", "/payments", "/payments/:paymentId"], };