I want to pass the data from the NextJS middleware to the client component. I am using NextJS for the frontend, and an Express API for the backend.
I could do it with X-Headers but what I want to send is user data and it is too sensitive to be sent in the headers. I already thought about sending only the ID and get the user from it fetching the API, but it would be a double request (same problem that I have now, by fetching twice /user/me).
Would making API routes solve the problem? I am also open to change my logic (remove middleware or any else).
Here is my actual middleware:
import { NextRequest, NextResponse } from "next/server";
import { getLoginUser } from "./lib/api/user/getLoginUser";
export default async function middleware(req: NextRequest) {
const url = req.nextUrl.pathname;
const cookies = req.cookies;
const user = await getLoginUser(cookies);
console.log(`🔐 AuthMiddleware - URL: ${url}, user: ${user}`);
if (user) {
console.log("✅ Middleware: Utilisateur déjà authentifié");
if (url.includes("auth")) {
console.log("🔄 Redirection vers le tableau de bord");
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.next();
} else {
console.log("❌ Middleware: Utilisateur non authentifié");
if (!url.includes("auth")) {
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
}
}
export const config = {
matcher:
"/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
};
-
yep working on thisruser26887079– user268870792025年11月20日 08:30:56 +00:00Commented Nov 20, 2025 at 8:30
1 Answer 1
There are various ways to implement auth, what you have done is good, but it is only a part of the puzzle. Depending on the type of application you are building - whether the data on the page is tightly coupled with the users themselves or static data that remains same for most users, you may get away without an auth check in the in the middleware. I strongly suggest having another check in the components that render the authorized data, as does Next.js.
If you are not heavily reliant on static data, do away with the auth in the middleware, and implement a combination of a user context provider and a DAL as described in the link above.
5 Comments
Explore related questions
See similar questions with these tags.