I’m having trouble accessing the cookies at the middleware.ts of my next.js app. I don’t know why it fails if I have another next.js app with the same structure and it works, I suppose that becase the other app uses Next.js 14. Whenever I navigate through my app and make the middleware available, I get this error: Error: Invariant: cookies() expects to have requestAsyncStorage, none available.
this is my middleware.ts:
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from "next/headers";
import { jwtDecode } from 'jwt-decode';
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
const cookieStore = cookies();
const jwt = cookieStore.get("zurii-hr-panel-token")?.value || "";
const origin = request.nextUrl.clone().origin;
if(jwt) {
const decoded = jwtDecode(jwt);
const currentTimestamp = Math.floor(Date.now() / 1000);
const validateJWT = decoded.exp && decoded.exp > currentTimestamp;
if (validateJWT) {
if(request.nextUrl.pathname==="/login") {
return NextResponse.redirect(`${origin}/collaborators`);
}
return NextResponse.next();
} else if(!validateJWT && request.nextUrl.pathname!=="/login") {
return NextResponse.redirect(`${origin}/login`);
}
} else if(!jwt && request.nextUrl.pathname!=="/login") {
return NextResponse.redirect(`${origin}/login`);
}
}
export const config = {
matcher: ["/", "/login", "/collaborators", "/settings", "/status"]
}
I don’t know what to do and I’ve been stuck for ages with this problem.