0

I'm facing an issue in my Next.js 15 application.

I am setting the jwtToken in the cookies when a user logs in. I have verified this through the browser's Application tab in the developer tools, where I can see the jwtToken properly set in the cookies. However, when I try to read the jwtToken in my middleware, it always returns undefined.

In rare cases, it doesn't return undefined and works as expected, but this is inconsistent and unreliable.

Here's the code for my middleware:

     import { NextResponse, NextRequest } from "next/server";

     export async function middleware(request: NextRequest) {

     const jwtToken = request.cookies.get("jwtToken");
     const token = jwtToken?.value as string;

     console.log(token);  // Logs 'undefined' most of the time

     if (!token) {
         return NextResponse.json(
          { message: "no token provided, access denied from middleware" },
          {
             status: 401,
          }
        );
      }
     }

     export const config = {
       matcher: ["/api/invoices/:path*"],
     };

1 Answer 1

0

Your issue is likely caused by the jwtToken cookie not being included in the request to the path specified in your matcher.

In Next.js, middleware runs on the Edge runtime and can only access cookies that are sent along with the incoming request.

If the cookie was set without the proper path, secure, or sameSite attributes, it might not be attached to requests—especially those made to routes like /api/invoices/*.

Also, if you’re using fetch() within an API route or a React Server Component and trying to access cookies on the server side, middleware is not the right place to do so.

Instead, you should use:

import { cookies } from 'next/headers';
const cookieStore = cookies();
const token = cookieStore.get('jwtToken');

This will allow you to reliably access cookies from the server side in Next.js 13+ and 14+.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.