nextjs-auth0: v4: Infinitely stacking cookies

Checklist

Description

  • v4 sdk creates a new additional transactional cookie each time the unauthenticated user navigates to the app
  • v4 logout does not remove said cookies

v3 does not create infinite cookies and does remove cookies on logout.

This eventually leads to a situation where the header of the request is too large.

Reproduction

  1. Be unauthenticated in your application (remove all cookies on that domain if you want)
  2. Navigate to a route in your application (receive a cookie)
  3. Navigate to another route in your application (receive another cookie)
  4. Repeat as many times as you wish
  5. Navigate to /auth/logout (receive another cookie, and cookies are not removed)

https://github.com/user-attachments/assets/21076f33-3c81-428b-b84b-4d566883cb4e

Additional context

N/A

nextjs-auth0 version

4.0

Next.js version

15.1.6

Node.js version

20.x

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 15
  • Comments: 18 (7 by maintainers)

Most upvoted comments

Indeed - we have a migration branch and every time we deploy it we immediately start hitting 413s. We can manually wipe our cookies and things seem OK, but obviously we aren’t expecting our users to do this. This is a blocking problem on the migration path, @tusharpandey13 have you folks had any luck isolating the root cause here? We can’t upgrade nextJS until v4 of this SDK is working more reliably.

We had some user reports of this in production. Sharing this hacky fix until there is a patch available. This is a snippet from our middleware function:

const reqCookieNames = req.cookies.getAll().map((cookie) => cookie.name);

const authRes = await auth0.middleware(req);
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.
    reqCookieNames.forEach((cookie) => {
      if (cookie.startsWith('__txn')) {
        authRes.cookies.delete(cookie);
      }
    });
  }

if (req.nextUrl.pathname.startsWith('/auth')) {
    // If the request is for the auth routes, short circuit the middleware chain and return the response
    return authRes;
 }

On /auth/login it will delete any stale __txn cookies before creating a new one. Important to get the existing cookies before you apply the auth0.middleware or else you will end up deleting the __txn cookie for the current login attempt.

Trying to migrate von v3 to v4 and immediately encountered this problem. Only had problems with the migration and now the app is breaking for users because of this. I wished this would be treated with a higher priority.

Curious why a unique transaction cookie name is necessary vs reusing the same name? I think that could solve the issue, even if the cookie doesn’t clear properly.

The unique transaction cookie solves the following issue:

  • User opens your App in Tab 1 and clicks Login (This sets a transaction cookie), gets redirected to Auth0 and does not finish logging in.
  • User opens your App in Tab 2 and clicks Login (This overrides the transaction cookie), same as above they do not finish logging in.
  • User goes back to Tab 1 and finishes logging in, when being redirect back to your app they get “Invalid State” because the transaction in the cookie if for Tab 2, and Tab 1 is overridden so the transaction data is lost.

This is solved by using a unique transaction cookie for each transaction that was started, but with its own consequences.

So it is important to know that once we would bring back a single transaction cookie in an opt-in way, you will be open for the above behavior again, which is also why I think it is important to find the actual root cause of the cookies stacking, and not the fact that they aren’t clearing, because I do think using a unique cookie per transaction should be the better configuration.

What I am curious to understand is what is causing these infinite stacking cookies, can you elaborate @jgeurts ? I see some inaccurate information in this thread, such as that the transaction cookie is not removed after logging in, which isn’t entirely accurate (see here), let me elaborate:

  • Whenever you start the login process, we set a unique transaction cookie.
  • If the login is completed, and you are logged in. That unique transaction cookie is deleted.

If the above is not happening, that is definitely a bug. But important in this case is to look at the single, unique cookie in isolation here.

What we do need to solve:

- If the login is completed with an error, and you are not logged in, we should delete the transaction cookie.

What does not happen is:

  • When login for transaction A is done, we do not clear any other transaction cookie.
  • When login for transaction A is started, but never completed (e.g. by clicking back), we never delete the transaction cookie.

The above is expected because v4 supports multiple transactions, clearing any unrelated transaction cookies will break that functionality. Instead, we rely on the cookies expiring after 1 hour and self-cleaning after an hour. Are you saying this is not happening?

Based on my understanding, the transaction cookies can only stack infinitly if you:

  • Keep clicking login and back
  • Have an infinite redirect between your Login endpoint and Auth0.

Both are not expected scenario’s and the second one should be solved differently.

That said, that does not mean we want to better understand what is going on, and even improve where we can. Can you help us understand?

Some solutions I can think of is to add a configuration options to the SDK that allows either:

  • Only use a single transaction cookie
  • Configure the expiration of the transaction cookie
  • Configure a max amount of transaction cookies

The latter won’t resolve the problem, but would reduce the timespan the cookies exist, reducing the chance for them to grow.

@tusharpandey13 do you have an ETA on a revised fix for this? We’re seeing random logout issues for some of our users recently which I suspect is related to v4 upgrade. Haven’t been able to identify a root cause but this seems like it could be a potential reason.

My team is experiencing this issue after upgrading to v4. We’re currently on ‘^4.6.1’ and using custom routes to keep the v3 paths of /api/auth/*.

 const auth0 = new Auth0Client({
    ...
    routes: {
      login: '/api/auth/login',
      logout: '/api/auth/logout',
      callback: '/api/auth/callback',
      backChannelLogout: '/api/auth/backchannel-logout',
    },
  })

I’ve added the middleware workaround outlined above but we’re still seeing 431s.

// middleware.ts

  const reqCookieNames = request.cookies.getAll().map((cookie) => cookie.name)
  if (request.nextUrl.pathname === '/api/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.
    reqCookieNames.forEach((cookie) => {
      if (cookie.startsWith('__txn')) {
        authResponse.cookies.delete(cookie)
      }
    })
  }

  // if path starts with /auth, let the auth middleware handle it
  if (
    pathname.startsWith('/auth') ||
    pathname.startsWith('/api/auth') ||
    pathname.startsWith('/v2/logout')
  ) {
    return authResponse
  }

  const session = await auth0.getSession(request)

  if (!session && pathname !== '/') {
    const { origin } = new URL(request.url)
    return NextResponse.redirect(
      `${origin}/api/auth/login?returnTo=${pathname}`
    )
  }

Maybe my middleware setup is bunk but I’m out of ideas.