Floky99
Floky99

Reputation: 732

NextJS middleware cookies issue

I wanted to check if user has a valid token inside the cookie before accessing /api routes on my NextJS app so I created a middleware which would check that. Somehow I am not able to extract the value from req.cookies in my middleware... I followed NextJS official docs (https://nextjs.org/docs/advanced-features/middleware). First of all TypeScript is already throwing error: Error [TypeError]: request.cookies.getAll is not a function and also Property 'value' does not exist on type 'string'. Did you mean 'valueOf'?ts(2551)

export function middleware(request: NextRequest) {
  const cookie = request.cookies.get("token")?.value;
  console.log(cookie);

  const allCookies = request.cookies.getAll();
  console.log(allCookies);

  const response = NextResponse.next();
  return response;
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: "/api/:path*",
};

Upvotes: 3

Views: 7399

Answers (2)

Daniel Brown
Daniel Brown

Reputation: 3062

It looks like either the docs or the types are incorrect?

The type for NextCookies in 12.2.x:

export declare class NextCookies extends Cookies {
    response: Request | Response;
    constructor(response: Request | Response);
    get: (key: string) => string | undefined;
    getWithOptions: (key: string) => GetWithOptionsOutput;
    set: (key: string, value: unknown, options?: CookieSerializeOptions | undefined) => this;
    delete: (key: string, options?: CookieSerializeOptions) => boolean;
    clear: (options?: CookieSerializeOptions) => void;
}

You'll notice that the method getAll is not defined. For what it's worth, I no longer get this error in 13.2.x

Upvotes: 0

AlwaysLearning
AlwaysLearning

Reputation: 146

You cannot read in middleware the cookie value. You can read the cookie value only server side e.g. getserversideprop

Upvotes: -5

Related Questions