nextjs-auth0: v4 middleware documentation is missing crucial details

Checklist

  • I have looked into the Readme, Examples, and FAQ and have not found a suitable solution or answer.
  • I have looked into the API documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Describe the problem you’d like to have solved

First of all, let me say that the migration to v4 has been one of the worst vendor SDK migrations I’ve witnessed in the last years. While the rest of the migration to Next 15 only took ~1 hour, dealing with Auth0 took the better part of 2 days. The v4 migration guide is lacking details and the documentation is incomplete. Also the example is missing details.

Describe the ideal solution

Have more thorough migration guide and docs.

Alternatives and current workarounds

After 2 days of trial and error I want to share what made it work for me in the end:

Middleware configuration: The new auth0.middleware is a black box. The v4 guide opens with

export async function middleware(request: NextRequest) {
  return await auth0.middleware(request)
}

which doesn’t give me any context on what the middleware returns, and how I need to use it with existing custom middleware.

The following example that checks the session is missing detail. This is my current version:


export async function middleware(req: NextRequest) {
  // some custom code to rewrite posthog ingestion here

  const authResponse = await auth0.middleware(req);

  // Process Auth0 middleware
  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;
  }

  const session = await auth0.getSession(req);
  // Redirect must only be applied if not logout, otherwise logout doesn't work.
  if (!session && !req.nextUrl.pathname.startsWith("/auth/logout")) {
    return NextResponse.redirect(new URL("/auth/login", req.nextUrl.origin));
  }

  // Auth0 middleware response *must* be returned, becuase of the headers.
  return authResponse;
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};

The workaround code for issue #1917 should be included in the migration guide because the bug broke the app for users. Also it is crucial to only redirect to login if there is no session and the requested route is not /logout, otherwise the logout is not working correctly. It is yet unclear how the auth0 middleware needs to be handled if it needs to be combined with the response of custom middleware. There might be cases where returning the whole response for all routes is not a viable solution.

Now to the changes in configuration. We, as probably many others have Vercel preview environments and require auth to work with dynamic URLs. I would highly recommend to include this into your docs, as initially setting this up did also cost me a day of trial and error.

Our solution in v3 with Next.js 14 was to define AUTH0_BASE_URL=https://$VERCEL_BRANCH_URL in the .env file, which we then committed. Then we needed to use following configuration in the route handler:

export const GET = handleAuth({
  login: handleLogin({
    authorizationParams: {
      redirect_uri: `${process.env.AUTH0_BASE_URL}/api/auth/callback`,
    },
    returnTo: process.env.AUTH0_BASE_URL,
  }),
  logout: handleLogout({
    returnTo: process.env.AUTH0_BASE_URL,
  }),
});

The new solution in v4 is to add following section to the next.config.js

  env: {
    APP_BASE_URL:
      process.env.VERCEL_ENV === "preview"
        ? `https://${process.env.VERCEL_BRANCH_URL}`
        : process.env.APP_BASE_URL,
  },

and to configure the auth0 client like so

export const auth0 = new Auth0Client({
  authorizationParameters: {
    redirect_uri: `${process.env.APP_BASE_URL}/auth/callback`,
    audience: "whatever used to be in the audience env var",
  },
});

Don’t forget to add wildcard domains to the allowed callback urls in the app config in Auth0.

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 10
  • Comments: 22 (7 by maintainers)

Most upvoted comments

Also randomly I’m getting The state parameter is invalid. on logins

We did some further digging and it looks like the state parameter issue is actually related to the cookie size exceeding 4096 bytes. Auth0 puts the permissions of the user in the accessToken and this accessToken is saved in your cookie. The fact that The state parameter is invalid happens is that the cookie is too big and this results in the cookie not being set, which then results in the state key not being found in the transactionCookie.

So to solve this, make your cookie smaller, and put it in a custom data store (like redis) or in your backend.

I found a fix to all these problems that were hurting our users experience: Migrate to Clerk. No problems since 😃

@Strernd We are having the same problem here. One other problem we have now, is that the session cookie size exceeds the 4096 bytes. Not sure if the state parameter problem is caused by that.

Update to the The state parameter is invalid problem:

  • I can not reproduce it in a newly intialized Nextjs project
  • I checked the application configuration (callback urls) multiple times

I can’t see what I’m doing, that is not canonical. This problem did not occur with v3. The migration to v4 caused it.

Hey, having the same problem. Can someone get some updates here? Customers are not happy 😦

I consistently get 431 Response too large when implementing things in 4.4.2. looking at the cookies, it appears that there is a very large amount of cookies created by the package and therefore making the request (headers) too large.

The randomly occurring The state parameter is invalid exceptions are really hurting our user experience. Is this repository actively maintained?