Keep auth state (server & client) in sync with path-based workspace in Next.js

Context
• Our app uses a path segment for the workspace slug: /w/<slug>.
• A middleware ensures the session’s active organization matches the path:
if (workspace.slug !== slug) {
  await betterFetch("/api/auth/organization/set-active", {
    baseURL: request.nextUrl.origin,
    headers: request.headers,
    method: "POST",
    body: { organizationSlug: slug },
  });
}


What works
• On the server, subsequent requests use the correct organization.
• The session on the server reflects the updated active workspace.

Problem
• On the client, the session isn’t re-fetched automatically after the middleware updates the active org.
• If I navigate between /w/a and /w/b, the client-side session remains stale (still points to the previous org).

Current workaround
• In a layout, I added a guard that compares the path slug with the client session/org and forces a re-fetch when they differ. It works but feels hacky.

Question
• Is there a way to trigger a refetch of the session from the middleware ?
• Do you have recommandation on url based organization ?

Stack
• Next.js (App Router)
• Better Auth
• Path-based multi-tenancy (/w/<slug>)

Thanks!
Was this page helpful?