Use Middleware to onboard users into organization

Hi everyone!

I'm building an app which makes it mandatory for a user to be in an organization since it is B2B. My initial thought was to write a middleware function that checks whether a user is affiliated with an organization (which a new user wouldn't be) and redirect them to an onboarding page (which is whitelisted from the middleware to avoid infinite loops) which will allow them to either create or join an existing organization (using an invite code, probably).

I'm currently using NextJS v15.3.1 with this method for getting the session inside my middleware, but the auth instance can't run since it is server side, and I can't use the authClient since that is meant for react components and doesn't work inside my middleware

import { betterFetch } from "@better-fetch/fetch";
import { auth } from "@lib/auth/server";
import { NextRequest, NextResponse } from "next/server";

type Session = typeof auth.$Infer.Session;

export async function middleware(request: NextRequest) {
  const { data: session } = await betterFetch<Session>(
    "/api/auth/get-session",
    {
      baseURL: request.nextUrl.origin,
      headers: {
        cookie: request.headers.get("cookie") || "", // Forward the cookies from the request
      },
    }
  );

  if (!session) {
    return NextResponse.redirect(new URL("/auth/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/app/:path*"], // Apply middleware to specific routes
};



I'd be grateful if anyone could give me an idea on how to do this, thanks in advance!
Integrate Better Auth with Next.js.
Was this page helpful?