I'm using Clerk to do user auth for my app's back office and i applied an organization on a user with the admin role on Clerk's dashboard. However when inside the Clerk middleware and trying to access user infos it shows the user but the orgId is undefined.
First, i applied org to user on Clerk dashboard :
Tried console.log the user infos with the auth() method provided in the afterAuth option :
import { authMiddleware, redirectToSignUp } from "@clerk/nextjs";
export default authMiddleware({
afterAuth(auth, req, evt) {
console.log(auth)
},
publicRoutes: [
"/api/albums/all",
"/",
"/player/(.*)",
"/login"
],
});
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};
This is the console.log result :
{
actor: undefined,
sessionClaims: {
azp: 'http://localhost:3000',
exp: 1698860167,
iat: 1698860107,
iss: 'https://able-pelican-18.clerk.accounts.dev',
nbf: 1698860097,
sid: 'sess_2XaGCNVMHEqLEujCfqDe88xxVo7',
sub: 'user_2XaG41***********RM8'
},
sessionId: 'sess_2XaGCNVMHEqLEujCfqDe88xxVo7',
session: undefined,
userId: 'user_2XaG41***********RM8',
user: undefined,
orgId: undefined,
orgRole: undefined,
orgSlug: undefined,
organization: undefined,
getToken: [Function],
debug: [Function],
isPublicRoute: true,
isApiRoute: true
}
orgId
only gives active Organization (Refer: https://clerk.com/docs/references/nextjs/authentication-object#authentication-object), but until unless we use we cannot set the active org. So to have this from the backend code we can use Clerk Node.js SDK and get org list of the user (either admin or a member) of the specified clerk account. One use-case is using the org list we can decide whether to redirect to/onboarding
or to the/dashboard
without client code (on route.ts for Next.js apps).No configuration is required for this, one single ENV variable as specified in [1].
Sample output:
In my case I did this inside
route.ts
(this can be done inafterAuth
function in middleware.ts):Hope this helps!!