> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Learn how to use the Management API Unlink a User Account endpoint to unlink an identity from the target user account making it a separate user account again.

# Unlink User Accounts

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Use the Auth0 <Tooltip tip="Management API: A product to allow customers to perform administrative tasks." cta="View Glossary" href="/docs/glossary?term=Management+API">Management API</Tooltip> [Unlink a User Account](https://auth0.com/docs/api/management/v2#!/Users/delete_user_identity_by_user_id) endpoint or the Auth0.js library to unlink an identity from the target user account making it a separate user account again.

The result of the unlinking process is the following:

* The secondary account is removed from the identities array of the primary account.
* A new secondary user account is created.
* The secondary account will have no metadata.

If your goal is to delete the secondary identity entirely, you must first unlink the accounts, and then [delete the newly created secondary account](/docs/manage-users/user-accounts/delete-users).

Depending on from where you call the endpoint, use one of these two scopes:

* `update:current_user_identities` from [client-side code](/docs/manage-users/user-accounts/user-account-linking/user-initiated-account-linking-client-side-implementation)
* `update:users` from [server-side code](/docs/manage-users/user-accounts/user-account-linking/suggested-account-linking-server-side-implementation)

The endpoint uses the following parameters:

| Parameter  | Type     | Description                                                                        |
| ---------- | -------- | ---------------------------------------------------------------------------------- |
| `id`       | `string` | ID of the primary user account (required)                                          |
| `provider` | `string` | identity provider name of the secondary linked account (e.g. `google-oauth2`)      |
| `user_id`  | `string` | ID of the secondary linked account (e.g. `123456789081523216417` part after the \` |

If your instance has users from multiple providers, you may also include `[connection_name]|` before the `user_id` stringto name the provider (for example, `"user-id": "google-oauth2|123456789081523216417").`

## Response example

```json lines theme={null}
[
  {
    "connection": "Initial-Connection",
    "user_id": "5457edea1b8f22891a000004",
    "provider": "auth0",
    "isSocial": false,
    "access_token": "",
    "profileData": {
      "email": "",
      "email_verified": false,
      "name": "",
      "username": "johndoe",
      "given_name": "",
      "phone_number": "",
      "phone_verified": false,
      "family_name": ""
    }
  }
]
```

## Use JWT from the primary account

To unlink accounts, call the Management API [Unlink a User Account endpoint](https://auth0.com/docs/api/v2#!/Users/delete_user_identity_by_user_id) using the <Tooltip tip="JSON Web Token (JWT): Standard ID Token format (and often Access Token format) used to represent claims securely between two parties." cta="View Glossary" href="/docs/glossary?term=JWT">JWT</Tooltip> from the primary account for authorization:

export const codeExample1 = `function unlinkAccount(secondaryProvider, secondaryUserId){
  var primaryUserId = localStorage.getItem('user_id');
  var primaryJWT = localStorage.getItem('id_token');
  $.ajax({
    type: 'DELETE',
    url: 'https://' + '{yourDomain}' + '/api/v2/users/' + primaryUserId +
         '/identities/' + secondaryProvider + '/' + secondaryUserId,
    headers: {
      'Authorization': 'Bearer ' + primaryJWT
    }
  }).then(function(identities){
    alert('unlinked!');
    showLinkedAccounts(identities);
  }).fail(function(jqXHR){
    alert('Error unlinking Accounts: ' + jqXHR.status + ' ' + jqXHR.responseText);
  });
}`;

<AuthCodeBlock children={codeExample1} language="javascript" />

## Use Access Token with the update:users scope

If you need to unlink two or more user accounts, call the Management API [Unlink a User Account endpoint](https://auth0.com/docs/api/v2#!/Users/delete_user_identity_by_user_id) using an [Management API Access Token](https://auth0.com/docs/api/v2/tokens) with the `update:users` scope.

```javascript lines theme={null}
function unlinkAccount(secondaryProvider, secondaryUserId) {
  var primaryUserId = localStorage.getItem('user_id');
  var primaryAccessToken = localStorage.getItem('access_token');

  // Uses the Access Token of the primary user as a bearer token to identify the account
  // which will have the account unlinked to, and the user id of the secondary user, to identify
  // the user that will be unlinked from the primary account.

  $.ajax({
    type: 'DELETE',
    url: 'https://' + AUTH0_DOMAIN +'/api/v2/users/' + primaryUserId +
         '/identities/' + secondaryProvider + '/' + secondaryUserId,
    headers: {
      'Authorization': 'Bearer ' + primaryAccessToken
    }
  }).then(function(identities){
    alert('unlinked!');
    showLinkedAccounts(identities);
  }).fail(function(jqXHR){
    alert('Error unlinking Accounts: ' + jqXHR.status + ' ' + jqXHR.responseText);
  });
}
```

## Unlink accounts from server-side code

1. Update the user in session with the new array of identities (each of which represent a separate user account).

```javascript lines theme={null}
const ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn();
const Auth0Client = require('../Auth0Client');
const express = require('express');
const router = express.Router();
...
router.post('/unlink-accounts/:targetUserProvider/:targetUserId',ensureLoggedIn, (req,res,next) => {
  Auth0Client.unlinkAccounts(req.user.id, req.params.targetUserProvider, req.params.targetUserId)
  .then( identities => {
    req.user.identities = req.user._json.identities = identities;
    res.send(identities);
  })
  .catch( err => {
    console.log('Error unlinking accounts!',err);
    next(err);
  });
});
```

1. Call the Management API v2 [Unlink a User Account endpoint](https://auth0.com/docs/api/v2#!/Users/delete_user_identity_by_user_id) using an [Management API Access Token](https://auth0.com/docs/api/v2/tokens) with the `update:users` scope.

export const codeExample2 = `const request = require('request');

class Auth0Client {
  ...
  unlinkAccounts(rootUserId, targetUserProvider, targetUserId){
    return new Promise((resolve,reject) => {
      var reqOpts = {
        method: 'DELETE',
        url: 'https://{yourDomain}/api/v2/users/' + rootUserId +
            '/identities/' + targetUserProvider + '/' + targetUserId,
        headers: {
          'Authorization': 'Bearer ' + process.env.AUTH0_APIV2_TOKEN
        }
      };
      request(reqOpts,(error, response, body) => {
        if (error) {
          return reject(error);
        } else if (response.statusCode !== 200) {
          return reject('Error unlinking accounts. Status: '+ response.statusCode + ' ' + JSON.stringify(body));
        } else {
          resolve(JSON.parse(body));
        }
      });
    });
  }
}

module.exports = new Auth0Client();`;

<AuthCodeBlock children={codeExample2} language="javascript" />

## Learn more

* [Link User Accounts](/docs/manage-users/user-accounts/user-account-linking/link-user-accounts)
* [User Account Linking: Server-Side Implementation](/docs/manage-users/user-accounts/user-account-linking/suggested-account-linking-server-side-implementation)
* [User-Initiated Account Linking: Client-Side Implementation](/docs/manage-users/user-accounts/user-account-linking/user-initiated-account-linking-client-side-implementation)
