# Organisation Member Invitation flow results in state mismatch

**URL:** <https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100>\
**Category:** Get Help\
**Tags:** organizations, nextjs, auth0\
**Created:** [September 22, 2021, 3:29pm UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100 "2021-09-22T15:29:39Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![nicky.thorne](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/nicky.thorne/32/13374_2.png) [@nicky.thorne](https://community.auth0.com/u/nicky.thorne)\
**Post date:** [September 22, 2021, 3:29pm UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100/1 "2021-09-22T15:29:39Z")

</div>

Please include the following information in your post:

SDK: nextjs-auth0  
SDK Version: 1.5.0  
Platform Version: Node v16.2.0

We are attempting to invite users to an organisation and are hitting an issue whereby the callback endpoints (within the default nextjs-auth0 `/api/auth/callback` endpoint is failing due to a state mismatch error).

Here are the steps taken:

1. Create Organisation using Management API ([Create Organizations](https://auth0.com/docs/organizations/configure/create-organizations#management-api))

2. Enable username/password connection for that Organisation using management API ([Enable Organization Connections](https://auth0.com/docs/organizations/configure/enable-connections#management-api))

3. Inviting a list of users to the newly created organisation using the Send Membership Invitations API ([Send Organization Membership Invitations](https://auth0.com/docs/organizations/configure/send-membership-invitations#management-api))

4. Invitee receives the invitation email with a login link (defined in tenant settings) which includes the invitation and organization parameters. Example URL `https://{host}/api/auth/login?invitation=xgHtmW8bgR0MdvMM3hM9yCPdKE6ufG9Y&organization=org_ssaeGaKNJBfrfsQ&organization_name=test`

5. Invitee receives the invitation email with a login link (defined in tenant settings) which includes the invitation and organization parameters. Example URL `https://{host}/api/auth/login?invitation=xgHtmW8bgR0MdvMM3hM9yCPdKE6ufG9Y&organization=org_ssaeGaKNJBfrfsQ&organization_name=test`

6. Modified the default login handler that nextjs-auth0 provides in order to forward the incoming organization and invitation params and set them as custom authorization params.

```auto
export default async function loginHandler(req: NextApiRequest, res: NextApiResponse) {
    return await handleLogin(req, res, {
        authorizationParams: {
            organization: req.query.organization as string,
            invitation: req.query.invitation as string,
        },
    });
}

```

1. The library redirects the user to the /authorize endpoint, forwarding the organization and invitation values and the user is presented with the custom organisation-branded invitation acceptance screen.  

2. The user enters a password, and clicks continue. They are presented with a consent page where they authorize the app.  

3. When accepted, auth0 redirects back to the callback handler in nextjs-auth0 with code and state parameters. `http://{host}/api/auth/callback?code=QgwBGJrS5suZZMBe&state=eyJyZXR1cm5UbyI6Imh0dHA6Ly9sb2NhbGhvc3Q6MzAwMS8ifQ`

This is where the callback handler in the SDK fails with an Error stating that there’s a state mismatch:

> state mismatch, expected eyJyZXR1cm5UbyI6Ii8ifQ, got: eyJyZXR1cm5UbyI6Imh0dHA6Ly9sb2NhbGhvc3Q6MzAwMS8ifQ

When decoding these state JWTs it’s because the `returnTo` values are different.  
SDK expects:

```auto
{
  "returnTo": "/"
}

```

Auth0 is sending:

```auto
{
  "returnTo": "http://localhost:3001/"
}

```

Question is why is Auth0 sending this value and why are these values different during the invitation process?

To attempt to fix this issue, I have added an implementation for `getLoginState` option in the `handleLogin` function, in order to send a fixed `returnTo` value of ‘[http://localhost:3001/](http://localhost:3001/)’.

```auto
    return await handleLogin(req, res, {
        getLoginState: () => {
            return {
                redirectTo: 'http://localhost:3001/',
            };
        },
        authorizationParams: {
            organization: req.query.organization as string,
            invitation: req.query.invitation as string,
        },

```

But this results in the following error:

> Error [BadRequestError]: checks.state argument is missing

This means the user hits an “Internal Server Error” page. The interesting this is that the whole invitation process seems to have work, and the invitee does have an active session. But the callback failing prevents the end-to-end flow from working seamlessly.

Any help would be greatly apprechiated.

---

<div class="post-metadata">

**Author:** ![amritk](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/amritk/32/36316_2.png) [@amritk](https://community.auth0.com/u/amritk)\
**Post date:** [April 1, 2022, 12:33am UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100/2 "2022-04-01T00:33:03Z")

</div>

hey @nicky.thorne I’m having this exact issue right now. Did you manage to find a solution?

---

<div class="post-metadata">

**Author:** ![nick18](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/nick18/32/40161_2.png) [@nick18](https://community.auth0.com/u/nick18)\
**Post date:** [November 15, 2022, 10:14pm UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100/3 "2022-11-15T22:14:32Z")

</div>

My guess here is that it’s because you are ignoring the `opts` from the originating request.

I was able to override the default login function like so, and it worked totally fine.

```auto
import { handleAuth, handleLogin } from '@auth0/nextjs-auth0';

export default handleAuth({
  login: (req, res, opts) => {
    return handleLogin(req, res, {
      ...opts,
      authorizationParams: {
        ...opts?.authorizationParams,
        invitation: getSingleOrUndefined(req.query.invitation),
        organization: getSingleOrUndefined(req.query.organization),
      },
    });
  },
});

function getSingleOrUndefined(
  item: string | string[] | undefined
): string | undefined {
  if (!item) {
    return undefined;
  }
  const newItem = Array.isArray(item) ? item[0] : item;
  return !newItem || newItem === 'undefined' ? undefined : newItem;
}

```

I’m not sure the implications of overriding the default login to include this. Honestly, it seems like this should just be baked in to the nextjs-auth0 library. Why do we have to override those so that invites are supported? Makes no sense really.

I had to spend a ton of time tracking this down when I sought out how to exactly invite someone to an organization, only to find that the default API endpoints don’t support it without modifications!

---

<div class="post-metadata">

**Author:** ![konrad.sopala](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/konrad.sopala/32/13516_2.png) [@konrad.sopala](https://community.auth0.com/u/konrad.sopala)\
**Post date:** [November 21, 2022, 11:36am UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100/4 "2022-11-21T11:36:45Z")

</div>

Thanks for sharing it with the rest of community!

---

<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:** [December 5, 2022, 11:37am UTC](https://community.auth0.com/t/organisation-member-invitation-flow-results-in-state-mismatch/70100/5 "2022-12-05T11:37:39Z")

</div>

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