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
};
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!
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
3 Replies
Rifki Salim
Rifki SalimOP5mo ago
Anyone?
MarkMiklos
MarkMiklos5mo ago
you can run auth in middleware since nextjs 15.2 and above allow nodejs runtime, maybe you missed out on this part? https://www.better-auth.com/docs/integrations/next#for-nextjs-release-1520-and-above
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
Rifki Salim
Rifki SalimOP5mo ago
Oh yeah about that, it says that I need to be on canary for the nodejs middleware to work. I am kind of worried whether it is stable enough for production I'll try that and report back anyway

Did you find this page helpful?