# Create and use organization on first login

**URL:** <https://community.auth0.com/t/create-and-use-organization-on-first-login/141045>\
**Category:** Get Help\
**Tags:** new-universal-login-experience, login-experience\
**Created:** [August 14, 2024, 12:55pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045 "2024-08-14T12:55:37Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex49](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@alex49](https://community.auth0.com/u/alex49)\
**Post date:** [August 14, 2024, 12:55pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045/1 "2024-08-14T12:55:37Z")

</div>

Ready to post? 🔍 First, try searching for your answer.  
Hey all, our use case is that we need to create an organization for each user when they first login. This has been easy enough to do with the `onExecutePostLogin` action, but the problem we are running into is that for the session the org was create, auth0 is not adding the `org_id` to the token, the user has to logout then back in. Would love some pointers on a better way to do this!

Right now, the best solution we’ve found is to add a custom claim on the ID Token after creating the organization (` api.idToken.setCustomClaim(`${namespace}`, org.data.id);`, then having a `useEffect` in our React layout that checks for a user without a `org_id`, and if so calls `loginWithPopup` passing the `org_id` from the custom claim.

```auto
useEffect(() => {
		if (user) {
			console.log(user)
			const refreshToken = async () => {
				if (!user.org_id) {
					const token = await loginWithPopup({
						authorizationParams: {
							organization: user['https://doohickey.ai/org_id']
						}
					})
				}
			}
			refreshToken()
		}
	}, [user])

```

This works, but results in screen flashing and a slow login. Additionally, we haven’t gotten this to work with anything but the Organizations-\>Both-\>Prompt for Credentials Universal Login setting. Which means that a user with a single org still has to select the org from the org list on subsequent logins, which is a bad user experience.

Our ideal flow would be user first login → action creates org → login flow resumes, user picks org → user authenticated and org\_id on token.

I’ve also experimented with clearing the session and redirected back to the authorize flow in the action, but this seems to lead to redirect loops (sample code from failed experiments below)

```auto
 await api.session.revoke("set org manually")
  api.redirect.sendUserTo(`https://dev-mhrta5blmbkurat0.us.auth0.com/authorize`,
  {
    query: {
      client_id: client_id
      audience: audience,
      response_type: 'token',
      redirect_uri: `http://localhost:5173/callback`,
      org_id: org.data.id,
      organization: org.data.id,
      scope: "openid profile email user_metadata"
    }
  });

```

For reference, this is the current state of our action:

```auto
const ManagementClient = require('auth0').ManagementClient;
const generate = require("random-words");

exports.onExecutePostLogin = async (event, api) => {
const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientID,
      clientSecret: event.secrets.clientSecret
  });
  
  const user = event.user.user_id
  
  const orgs = await management.users.getUserOrganizations({id: user})

  if(orgs?.data?.length) {
    api.idToken.setCustomClaim(event.secrets.namespace, orgs.data[0].id);
    return;
  }

  let name = ""
  let tries = 3

  while(tries > 0) {
    name = generate({ exactly: 3, minLength: 3, join: "-" })
    tries--
    try {
      const existing = await management.organizations.getByName({
        "name": name
      })
      if (!existing?.data?.name) break;
    } catch (_e) {
      break
    }
  }

  const data = {"name": name}

  const org = await management.organizations.create(data)
  var params = { id : org.data.id}
  await management.organizations.addEnabledConnection(params, {
    connection_id: event.secrets.connId
  })

  var dataOrg = { members: [user] }

  await management.organizations.addMembers(params, dataOrg)
  api.idToken.setCustomClaim(event.secrets.namespace, org.data.id);
  
}

```

Thanks for any help!

---

<div class="post-metadata">

**Author:** ![volodymyr.machula](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/volodymyr.machula/32/61679_2.png) [@volodymyr.machula](https://community.auth0.com/u/volodymyr.machula)\
**Post date:** [October 23, 2024, 10:59pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045/2 "2024-10-23T22:59:35Z")

</div>

We have exactly the same problem. @alex49 have you found how to resolve it?

---

<div class="post-metadata">

**Author:** ![atzinov](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/atzinov/32/48806_2.png) [@atzinov](https://community.auth0.com/u/atzinov)\
**Post date:** [March 3, 2025, 5:03pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045/3 "2025-03-03T17:03:49Z")

</div>

We also have the exact same use case and need. We will be trying to implement the above setup as a short-term stop gap, but would love to see what Auth0 recommends implementing to achieve this.

---

<div class="post-metadata">

**Author:** ![nik.baleca](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/nik.baleca/32/68749_2.png) [@nik.baleca](https://community.auth0.com/u/nik.baleca)\
**Post date:** [March 3, 2025, 7:19pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045/5 "2025-03-03T19:19:05Z")

</div>

Hi @alex49 and everyone else!

Welcome to the Auth0 Community!

I am sorry about the late reply to your inquiry.

Auth0 does not offer an out-of-the-box solution for your use case. Organizations are intended to be created prior to a user logging in and joining one, meaning that creating one during the first login of a user as you have attempted can present some limitations and difficulties.

The workaround you have presented appears to be a valid workaround, however I am not sure why the users who belong to a single organization would be redirected to an organization picker since they should be redirected to the organization login directly.

Unfortunately, without having the user re-authenticate themselves after creating the organization, it would not be possible to achieve it.

I would highly recommend to post on our [Feedback](https://community.auth0.com/c/feedback/95) page regarding this use case.

If you have any other questions, feel free to leave a reply or post again on the community!

Kind Regards,  
Nik

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [March 17, 2025, 7:19pm UTC](https://community.auth0.com/t/create-and-use-organization-on-first-login/141045/6 "2025-03-17T19:19:45Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
