Create middleswares

This commit is contained in:
g
2025-02-07 22:21:26 +00:00
parent b94391c8d5
commit 80eb0a6c1b
2 changed files with 34 additions and 3 deletions

View File

@@ -8,9 +8,6 @@ export async function clientFetch(url: string, options: RequestInit = {}): Promi
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || localStorage.getItem('Authorization');
console.log('authToken', authToken);
// Merge Authorization header if token is found
const headers = {
'Content-Type': 'application/json',
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),

34
middleware.ts Normal file
View 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*"],
};