unable to retrieve the JSON data returned from the fetch API call in the middleware of Next.js
Unanswered
Araucanian herring posted this in #help-forum
Araucanian herringOP
I am currently working on implementing role-based authentication with JWT using Next.js middleware. In my specific scenario, once a user successfully logs in, a JWT token is generated. I then retrieve the user's data from the endpoint http://localhost:3000/api/me. If the token is available, it returns the user's ID and role (
When a user logs in successfully, I can retrieve their user data by entering the following API endpoint in the browser: http://localhost:3000/api/me. However, when I attempt to retrieve the user data from the middleware, it returns an unauthorized message instead.
middleware.ts
{"user":{"id":"649eaab9129b600eaccd800a","role":"admin"}}); otherwise, it returns an unauthorized message {"message":"Unauthorized"}.When a user logs in successfully, I can retrieve their user data by entering the following API endpoint in the browser: http://localhost:3000/api/me. However, when I attempt to retrieve the user data from the middleware, it returns an unauthorized message instead.
middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
const token = request.cookies.get("token")?.value;
const response = await fetch("http://localhost:3000/api/me");
const { user } = await response.json();
if (!token && !user?.role) {
if (!request.nextUrl.pathname.startsWith("/login")) {
return NextResponse.redirect(new URL("/login", request.url));
}
} else if (
token &&
user?.role &&
!request.nextUrl.pathname.startsWith(`/${user?.role}`) &&
!request.nextUrl.pathname.startsWith("/login")
) {
return NextResponse.redirect(new URL("/access", request.url));
} else {
if (!request.nextUrl.pathname.startsWith(`/${user?.role}`)) {
return NextResponse.redirect(new URL(`/${user?.role}`, request.url));
}
}
}
export const config = {
matcher: ["/admin/:path*", "/superadmin/:path*", "/user/:path*", "/login"],
};