Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v4 middleware documentation is missing crucial details #1983

Open
5 tasks done
Strernd opened this issue Mar 20, 2025 · 2 comments
Open
5 tasks done

v4 middleware documentation is missing crucial details #1983

Strernd opened this issue Mar 20, 2025 · 2 comments

Comments

@Strernd
Copy link

Strernd commented Mar 20, 2025

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

@Strernd
Copy link
Author

Strernd commented Mar 20, 2025

Update: Still experiencing flakiness with logout (directly back to start page when clicking logout)

@Strernd
Copy link
Author

Strernd commented Mar 21, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant