sarlink-portal/middleware.ts

39 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-11-24 23:30:44 +05:00
import { betterFetch } from "@better-fetch/fetch";
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";
console.log(protocol)
console.log(host)
try {
const { data: session } = await betterFetch<Session>(
"http://localhost:3000/api/auth/get-session",
{
baseURL: `${protocol}://${host}`,
headers: {
//get the cookie from the request
cookie: request.headers.get("cookie") || "",
host: host
},
2025-01-11 04:31:04 +05:30
},
2025-01-11 05:31:13 +05:30
);
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) {
console.log("Middlewaree", 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 = {
matcher: ["/devices", "/", "/payments", "/payments/:paymentId"],
2024-11-24 23:30:44 +05:00
};