I’ve encountered an issue with next/Link
while using middleware.js
for authenticate and authorization .The problem arises When I click on header links ,which trigger a request to the server to retrieve the user’s profile .Initially the middleware checks if the user exists ;if not ,it redirects the user to /auth
. After authenticating in the app ,I click on the /profile
link in header ,but it doesn’t work for the subsequence requests using <Link href="/profile"> profile </Link>
and still in /auth
route .however if I use <a href="/profile"> profile </a>
,everything works as expected.
header.js
"use client";
import { useUser } from "@/hooks/useUser";
import Link from "next/link";
function HeaderApp() {
const { profile, isLoading } = useUser();
return (
<header className="border-b">
<ul className="flex justify-evenly">
<li className="p-4">
<Link href="/">home</Link>
</li>
<li className="p-4">
<Link href="/profile">profile</Link>
</li>
<li className="p-4">
<Link href="/admin">admin</Link >
</li>
<li className="p-4">
<Link href="/auth">login</Link>
</li>
</ul>
</header>
);
}
export default HeaderApp;
and
middleware.js
import { middlewareAuth } from "./utils/middlewareAuth";
export async function middleware(req) {
const url = req.url;
const pathname = req.nextUrl.pathname;
if (pathname.startsWith("/profile")) {
const user = await middlewareAuth(req);
if (!user) return NextResponse.redirect(new URL("/auth", url));
}
if (pathname.startsWith("/cart")) {
const user = await middlewareAuth(req);
if (!user) return NextResponse.redirect(new URL("/auth", url));
}
if (pathname.startsWith("/admin")) {
const user = await middlewareAuth(req);
if (!user) return NextResponse.redirect(new URL("/auth", url));
if (user && user.role !== "ADMIN")
return NextResponse.redirect(new URL("/", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/profile/:path*", "/cart/:path*"],
};
I use nextjs 14