Create middleswares
This commit is contained in:
34
middleware.ts
Normal file
34
middleware.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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 {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/me`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
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*"],
|
||||
};
|
||||
Reference in New Issue
Block a user