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)$).*)",
};