Skip to content

4.3: The cookie size exceeds 4096 bytes #2011

Closed
@robcaldecott

Description

@robcaldecott

Checklist

Description

Just upgraded from 4.1 to 4.3 and am seeing the following message:

The cookie size exceeds 4096 bytes, which may cause issues in some browsers. Consider removing any unnecessary custom claims from the access token or the user profile. Alternatively, you can use a stateful session implementation to store the session data in a data store.

I have tried logging out and clearing cookies and the issue persists. Our middleware.ts looks something like this:

export async function middleware(req: NextRequest) {
  // Handle auth-specific routes
  const authResponse = await auth0.middleware(req);
  if (req.nextUrl.pathname.startsWith("/auth")) {
    if (req.nextUrl.pathname === "/auth/login") {
      // This is a workaround for this issue: https://github.com/auth0/nextjs-auth0/issues/1917
      // The auth0 middleware sets some transaction cookies that are not deleted after the login flow completes.
      // This causes stale cookies to be used in subsequent requests and eventually causes the request header to be rejected because it is too large.
      const reqCookieNames = req.cookies.getAll().map((cookie) => cookie.name);
      reqCookieNames.forEach((cookie) => {
        if (cookie.startsWith("__txn")) {
          authResponse.cookies.delete(cookie);
        }
      });
    }
    return authResponse;
  }

  // Do we have a token?
  const accessToken = await auth0.getAccessToken();
  if (!accessToken) {
    return NextResponse.redirect(
      new URL(`/auth/login?returnTo=${req.nextUrl.pathname}`, req.url),
    );
  }
  return authResponse;
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     * - hc (health check)
     * - unauthorised (user not authorised page)
     */
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|hc|unauthorised).*)",
  ],
};

Reverting to 4.1 fixes the issue.

Here is how the cookies look on 4.3

Image

And on 4.1

Image

Reproduction

See above

Additional context

No response

nextjs-auth0 version

4.3

Next.js version

15.2.4

Node.js version

20

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions