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