Organization Logic

How to handle logic to make sure that when user access layout in nextjs, its already have user and organization value?

const headerList = await headers();
  const session = await auth.api.getSession({ headers: headerList });
  if (!session) {
    redirect("/auth/login");
  }
  const activeOrgId = session.session.activeOrganizationId;
  // get all org by user
  const allOrgs = await auth.api.listOrganizations({
    headers: headerList,
  });
  // if user doesnt have org , redirect to onboarding
  if (allOrgs.length === 0) {
    redirect("/app/onboarding");
  }
  // if user doesnt have active org , set active org from orglist
  if (!activeOrgId && allOrgs.length > 0) {
    await auth.api.setActiveOrganization({
      headers: headerList,
      body: {
        organizationId: allOrgs[0].id,
      },
    });
  }
  // if user have active org in session, but after searching in db, the org is not found, redirect to onboarding
  if (activeOrgId && !allOrgs.some((org) => org.id === activeOrgId)) {
    redirect("/app/onboarding");
  }

//render
Was this page helpful?