> ## Documentation Index
> Fetch the complete documentation index at: https://auth0-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> How to install, initialize and use Auth0.js

# Auth0.js

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>;
};

The Auth0.js library is a client-side JavaScript library for Auth0. It supports both [hosted login and embedded login](/docs/authenticate/login/universal-vs-embedded-login) use cases. This article covers **v10**, the current version.

Review the [full API documentation for the library](https://auth0.github.io/auth0.js/index.html).

## Migrate from v9 to v10

Auth0.js v10 contains a security fix for CVE-2026-42280 and one breaking change:

| Affected         | Details                                                                                                                                                                                                                                                    |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Apps using RS256 | No breaking change                                                                                                                                                                                                                                         |
| Apps using HS256 | `parseHash()` now returns an `invalid_token` error instead of silently succeeding. Switch to RS256 in the Auth0 Dashboard: **Applications** > your app > **Settings** > **Advanced Settings** > **OAuth** > **JsonWebToken Signature Algorithm** > `RS256` |

If you need the v9 API reference, see the [auth0-js package on npm](https://www.npmjs.com/package/auth0-js?activeTab=versions) and select your v9 version, or browse the [v9 source and changelog on GitHub](https://github.com/auth0/auth0.js).

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Embedded login for web applications uses [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) unless you [configure a custom domain](/docs/customize/custom-domains) for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
</Callout>

## Ready-to-go example

The [example directory](https://github.com/auth0/auth0.js/tree/master/example) of the Auth0.js library is a ready-to-go app that can help you to quickly and easily try out Auth0.js. To run it:

1. If you don't have [node](http://nodejs.org/) installed, do that now
2. Download dependencies by running `npm install` from the root of this project
3. Finally, execute `npm start` from the root of this project, and then browse to your app running on the node server, presumably at `http://localhost:3000/example`.

## Setup and initialization

The following sections cover [methods of installation](#installation-options), [how to initialize Auth0.js](#initialization), [signup](#signup), [login](#login), [logout](#logout), and more.

### Configure your Auth0 application for embedded login

When implementing embedded login, the library uses cross-origin calls inside hidden iframes to perform authentication. To make sure this can be done securely, Auth0 needs to know the domains where you host your applications.

Add the domain to the **Allowed Web Origins** field. You can find this field in the [Application Settings](https://manage.auth0.com/#/applications) area of your Dashboard.

### Installation options

You have a few options for using Auth0.js in your project. Pick one of the below depending on your needs:

Install via [npm](https://npmjs.org) or [yarn](https://yarnpkg.com):

```bash lines theme={null}
npm install auth0-js

yarn add auth0-js
```

After installing the `auth0-js` module, bundle it up along with all of its dependencies, or import it using:

```js lines theme={null}
import auth0 from 'auth0-js';
```

Alternatively, include the script through the CDN:

```html wrap lines theme={null}
<script src="https://cdn.auth0.com/js/auth0/10.0.0/auth0.min.js"></script>
```

### Initialization

Initialize a new instance of the Auth0 application as follows:

export const codeExample1 = `<script type="text/javascript">
  var webAuth = new auth0.WebAuth({
    domain:       '{yourDomain}',
    clientID:     '{yourClientId}'
  });
</script>`;

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

#### Available parameters

There are two required parameters that must be passed in the `options` object when instantiating `webAuth` and more that are optional.

| **Parameter**                 | **Required** | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `domain`                      | required     | (String) Your Auth0 account domain (ex. myaccount.auth0.com)                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `clientID`                    | required     | (String) Your Auth0 client ID                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `redirectUri`                 | optional\*   | (String) The default `redirectUri` used. Defaults to an empty string (none). **If you do not provide a global `redirectUri` value here, you will need to provide a redirectUri value for *each* method you use.**                                                                                                                                                                                                                                                                       |
| `scope`                       | optional     | (String) The default <Tooltip tip="Scope: Mechanism that determines actions applications can perform on a user's behalf with information previously created in an online resource." cta="View Glossary" href="/docs/glossary?term=scope%28s%29">scope(s)</Tooltip> used by the application. Using scopes can allow you to return specific claims for specific fields in your request. You should read our [documentation on scopes](/docs/get-started/apis/scopes) for further details. |
| `audience`                    | optional     | (String) The default audience to be used for requesting API access.                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `responseType`                | optional\*   | (String) The default `responseType` used. It can be any space separated list of the values `code`, `token`, `id_token`. It defaults to `'token'`, unless a `redirectUri` is provided, then it defaults to `'code'`. **If you do not provide a global `responseType` value, you will need to provide a `responseType` value for *each* method you use.**                                                                                                                                 |
| `responseMode`                | optional     | (String) This option is omitted by default. Can be set to `'form_post'` in order to send the token or code to the `'redirectUri'` via POST. Supported values are `query`, `fragment` and `form_post`.                                                                                                                                                                                                                                                                                   |
| `leeway`                      | optional     | (Integer) A value in seconds; leeway to allow for clock skew with regard to ID Token expiration times.                                                                                                                                                                                                                                                                                                                                                                                  |
| `_disableDeprecationWarnings` | optional     | (Boolean) Disables the deprecation warnings, defaults to `false`.                                                                                                                                                                                                                                                                                                                                                                                                                       |

Because of clock skew issues, you may occasionally encounter the error `The token was issued in the future`. The `leeway` parameter can be used to allow a few seconds of leeway to ID Token expiration times, to prevent that from occurring.

##### Scope

The default `scope` value in Auth0.js v10 is `openid profile email`.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  **Running Auth0.js locally**

  If you don't specify at least the above scope when initializing Auth0.js, and you are running your website from `http://localhost` or `http://127.0.0.1`, calling the `getSSOData()` method will result in the following error in the browser console:

  `Consent required. When using getSSOData, the user has to be authenticated with the following scope: openid profile email`

  That will not happen when you run your application in production or if you specify the `openid profile email` scope. You can read more about this in the [User consent and third-party applications](/docs/get-started/applications/third-party-applications/user-consent-and-third-party-applications) document.
</Callout>

## Login

You can choose a method for login based on the type of authentication you need in your application.

### webAuth.authorize()

The `authorize()` method can be used for logging in users through <Tooltip tip="Universal Login: Your application redirects to Universal Login, hosted on Auth0's Authorization Server, to verify a user's identity." cta="View Glossary" href="/docs/glossary?term=Universal+Login">Universal Login</Tooltip> or social connections as shown in the examples below. This method invokes the `/authorize` endpoint of the Authentication API, and can take a variety of parameters through the `options` object.

| **Parameter**  | **Required** | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| -------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audience`     | optional     | (String) The default audience to be used for requesting API access.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `connection`   | optional     | (String) Specifies the connection to use rather than presenting all connections available to the application.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `scope`        | optional     | (String) The scopes which you want to request authorization for. These must be separated by a space. You can request any of the standard OIDC scopes about users, such as `profile` and `email`, custom claims that must [conform to a namespaced format](/docs/secure/tokens/json-web-tokens/create-custom-claims), or any scopes supported by the target API (for example, `read:contacts`). Include `offline_access` to get a <Tooltip tip="Refresh Token: Token used to obtain a renewed Access Token without forcing users to log in again." cta="View Glossary" href="/docs/glossary?term=Refresh+Token">Refresh Token</Tooltip>. |
| `responseType` | optional     | (String) It can be any space separated list of the values `code`, `token`, `id_token`. It defaults to `'token'`, unless a `redirectUri` is provided, then it defaults to `'code'`.                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `clientID`     | optional     | (String) Your Auth0 client ID.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `redirectUri`  | optional     | (String) The URL to which Auth0 will redirect the browser after authorization has been granted for the user.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `state`        | optional     | (String) An arbitrary value that should be maintained across redirects. It is useful to mitigate CSRF attacks and for any contextual information (for example, a return URL) that you might need after the authentication process is finished. For more information, see [State Parameter](/docs/secure/attack-protection/state-parameters). Auth0.js, when used in single-page applications, handles the state generation and validation automatically if not specified.                                                                                                                                                               |
| `prompt`       | optional     | (String) A value of `login` will force the login page to show regardless of current session. A value of `none` will attempt to bypass the login prompts if a session already exists (see the [silent authentication](/docs/authenticate/single-sign-on#silent-authentication) documentation for more details).                                                                                                                                                                                                                                                                                                                          |

For hosted login, one must call the `/authorize()` method.

`webAuth.authorize({//Any additional options can go here});`

For social logins, the `connection` parameter will need to be specified:

`webAuth.authorize({connection: 'twitter'});`

### webAuth.popup.authorize()

For popup authentication the `popup.authorize` method can be used. Popup authentication cannot be used within hosted login pages. Typically, popup authentication is used by single-page applications so the current state is not lost by doing a full page redirection.

Default authorization with popup (Universal Login):

```js lines theme={null}
webAuth.popup.authorize({
  responseType: 'token'
  redirectUri: 'https://YOUR_APP/popup_response_handler.html'
  //Any additional options can go here
}, function(err, authResult) {
  //do something
});
```

And for social login with popup using `authorize`:

```js lines theme={null}
webAuth.popup.authorize({
  responseType: 'token'
  redirectUri: 'https://{yourApp}/popup_response_handler.html',
  connection: 'twitter'
}, function(err, authResult) {
  //do something
});
```

#### Handle popup authentication results

When using popup authentication, you'll have to provide a `redirectUri` where the destination page communicates the authorization results back to the callback by using the `webAuth.popup.callback` method. A simple implementation would be something like this:

```html lines theme={null}
<!-- popup_response_handler.html -->
<html>
  <body>
    <script src="https://cdn.auth0.com/js/auth0/10.0.0/auth0.min.js"></script>
    <script type="text/javascript">
      var webAuth = new auth0.WebAuth({
        domain:       'YOUR_DOMAIN',
        clientID:     'YOUR_CLIENT_ID'
      });
      webAuth.popup.callback();
    </script>
  </body>
</html>
```

An ideal handler would contain only this minimal functionality (that is, avoid reloading the whole application just to handle the response).

You will need to add the `redirectUri` to the application's **Allowed Callback URLs** list in the application configuration page on the Dashboard.

### webAuth.login()

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Embedded login for web applications uses [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) unless you [configure a custom domain](/docs/customize/custom-domains) for your tenant. Cross-origin authentication uses third-party cookies to allow for secure authentication transactions across different origins.
</Callout>

The `login` method can be used for embedded login through [cross-origin authentication](/docs/authenticate/login/cross-origin-authentication) for database connections, using `/co/authenticate`.

| **Parameter** | **Required** | **Description**                                                                                        |
| ------------- | ------------ | ------------------------------------------------------------------------------------------------------ |
| `username`    | optional     | (String) The username to present for authentication. **Either** `username` or `email` must be present. |
| `email`       | optional     | (String) The email to present for authentication. **Either** `username` or `email` must be present.    |
| `password`    | required     | (String) The password to present for authentication.                                                   |
| `realm`       | required     | (String) The name of the database connection against which to authenticate.                            |

```js lines theme={null}
webAuth.login({
  realm: 'tests',
  username: 'testuser',
  password: 'testpass',
});
```

### webAuth.crossOriginVerification()

The `crossOriginVerification()` method can be used to help provide cross-origin authentication to customers who have third-party cookies disabled in their browsers. To learn more about its usage, read [Cross-Origin Authentication](/docs/authenticate/login/cross-origin-authentication).

### buildAuthorizeUrl(options)

The `buildAuthorizeUrl` method can be used to build the `/authorize` URL, in order to initialize a new transaction. Use this method if you want to implement browser based (passive) authentication.

export const codeExample2 = `// Calculate URL to redirect to
var url = webAuth.client.buildAuthorizeUrl({
  clientID: '{yourClientId}', // string
  responseType: 'token id_token', // code
  redirectUri: 'https://{yourApp}/callback',
  state: '{yourState}',
  nonce: '{yourNonce}'
});

// Redirect to url
// ...`;

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

The `state` parameter is an opaque value that Auth0 will send back to you. This method helps prevent CSRF attacks, and it needs to be specified if you redirect to the URL yourself instead of calling `webAuth.authorize()`. For more information, see [State Parameter](/docs/secure/attack-protection/state-parameters).

### Single Sign-On with embedded authentication

Embedded login supports <Tooltip tip="Single Sign-On (SSO): Service that, after a user logs into one applicaton, automatically logs that user in to other applications." cta="View Glossary" href="/docs/glossary?term=Single+Sign-on">Single Sign-on</Tooltip> (SSO) when your applications share the following architecture:

1. The applications attempting SSO are first-party applications. Sharing embedded sessions with third-party applications is not supported.
2. The applications and your Auth0 tenant share a top-level domain via a [custom domain](/docs/customize/custom-domains). Traditional Auth0 domains use the `foo.auth0.com` format; custom domains let your applications and Auth0 tenant share the same top-level domain, which also helps prevent CSRF attacks.

When your architecture meets these criteria, embedded SSO with Auth0.js is a good fit. Universal Login handles SSO across multiple domains or with [third-party applications](/docs/get-started/applications/third-party-applications/configure-third-party-applications) automatically through its session layer, and the two can coexist in the same app—for example, Universal Login for primary sign-in and Auth0.js for embedded factor enrollment or step-up flows. To compare the trade-offs, read [Hosted Login vs. Embedded Login](/docs/authenticate/login/universal-vs-embedded-login).

## Passwordless login

<Tooltip tip="Passwordless: Form of authentication that does not rely on a password as the first factor." cta="View Glossary" href="/docs/glossary?term=Passwordless">Passwordless</Tooltip> authentication allows users to log in by receiving a one-time password through email or text message. The process will require you to start the passwordless process, generating and dispatching a code to the user (or a code within a link), followed by accepting their credentials through the verification method. That could happen in the form of a login screen which asks for their (email or phone number) and the code you just sent them. It could also be implemented in the form of a passwordless link instead of a code sent to the user. They would simply click the link in their email or text and it would hit your endpoint and verify this data automatically using the same verification method (just without manual entry of a code by the user).

To use passwordless authentication, initialize Auth0.js with a `redirectUri` and set `responseType: 'token'`.

export const codeExample3 = `var webAuth = new auth0.WebAuth({
  clientID: '{yourClientId}',
  domain: '{yourDomain}',
  redirectUri: 'http://example.com',
  responseType: 'token id_token'
});`;

<AuthCodeBlock children={codeExample3} language="js" />

### Start passwordless authentication

The first step in passwordless authentication with Auth0.js is the `passwordlessStart` method, which has several parameters which can be passed within its `options` object:

| **Parameter** | **Required** | **Description**                                                                                  |
| ------------- | ------------ | ------------------------------------------------------------------------------------------------ |
| `connection`  | required     | (String) Specifies how to send the code/link to the user. Value must be either `email` or `sms`. |
| `send`        | required     | (String) Value must be either `code` or `link`. If `null`, a link will be sent.                  |
| `phoneNumber` | optional     | (String) The user's phone number for delivery of a code or link via SMS.                         |
| `email`       | optional     | (String) The user's email for delivery of a code or link via email.                              |

Note that exactly one of the optional `phoneNumber` and `email` parameters must be sent in order to start the passwordless transaction.

```js lines theme={null}
webAuth.passwordlessStart({
    connection: 'email',
    send: 'code',
    email: 'foo@bar.com'
  }, function (err,res) {
    // handle errors or continue
  }
);
```

### Complete passwordless authentication

If sending a code, you will then need to prompt the user to enter that code. You will process the code, and authenticate the user, with the `passwordlessLogin` method, which has several parameters which can be sent in its `options` object:

| **Parameter**      | **Required** | **Description**                                                                                                                                          |
| ------------------ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connection`       | required     | (String) Specifies how to send the code/link to the user. Value must be either `email` or `sms` and the same as the value passed to `passwordlessStart`. |
| `verificationCode` | required     | (String) The code sent to the user, either as a code or embedded in a link.                                                                              |
| `phoneNumber`      | optional     | (String) The user's phone number to which the code or link was delivered via SMS.                                                                        |
| `email`            | optional     | (String) The user's email to which the code or link was delivered via email.                                                                             |

As with `passwordlessStart`, exactly one of the optional `phoneNumber` and `email` parameters must be sent in order to verify the passwordless transaction.

To use `passwordlessLogin`, specify `redirectUri` and `responseType` when initializing WebAuth.

```js lines theme={null}
webAuth.passwordlessLogin({
    connection: 'email',
    email: 'foo@bar.com',
    verificationCode: '389945'
  }, function (err,res) {
    // handle errors or continue
  }
);
```

## Extract the authResult and get user info

After authentication occurs, you can use the `parseHash` method to parse a URL hash fragment when the user is redirected back to your application in order to extract the result of an Auth0 authentication response. You may choose to handle this in a callback page that will then redirect to your main application, or in-page, as the situation dictates.

The `parseHash` method takes an `options` object that contains the following parameters:

| **Parameter**                                                                                                                                                                               | **Required** | **Description**                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `state`                                                                                                                                                                                     | optional     | (String) An opaque value the application adds to the initial request that Auth0 includes when redirecting back to the application. This value is used by Auth0.js to prevent CSRF attacks. |
| <Tooltip tip="Nonce: Arbitrary number issued once in an authentication protocol to detect and prevent replay attacks." cta="View Glossary" href="/docs/glossary?term=nonce">nonce</Tooltip> | optional     | (String) Used to verify the ID Token                                                                                                                                                       |
| `hash`                                                                                                                                                                                      | optional     | (String) The URL hash (if not provided, `window.location.hash` will be used by default)                                                                                                    |

The contents of the authResult object returned by `parseHash` depend upon which authentication parameters were used. It can include:

| **Item**      | **Description**                                                                                                                                                                                                                                      |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessToken` | An <Tooltip tip="Access Token: Authorization credential, in the form of an opaque string or JWT, used to access an API." cta="View Glossary" href="/docs/glossary?term=Access+Token">Access Token</Tooltip> for the API, specified by the `audience` |
| `expiresIn`   | A string containing the expiration time (in seconds) of the `accessToken`                                                                                                                                                                            |
| `idToken`     | An ID Token JWT containing user profile information                                                                                                                                                                                                  |

```js lines theme={null}
webAuth.parseHash({ hash: window.location.hash }, function(err, authResult) {
  if (err) {
    return console.log(err);
  }

  webAuth.client.userInfo(authResult.accessToken, function(err, user) {
    // Now you have the user's information
  });
});
```

As shown above, the `client.userInfo` method can be called passing the returned `accessToken`. It will make a request to the `/userinfo` endpoint and return the `user` object, which contains the user's information, formatted similarly to the below example.

```json lines theme={null}
{
    "sub": "auth0|123456789012345678901234",
    "nickname": "johnfoo",
    "name": "johnfoo@gmail.com",
    "picture": "https://gravatar.com/avatar/example.png",
    "updated_at": "2018-05-07T14:16:52.013Z",
    "email": "johnfoo@gmail.com",
    "email_verified": "false"
}
```

You can now do something else with this information as your application needs, such as acquire the user's entire set of profile information with the <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>, as described below.

## Using nonces

By default (and if `responseType` contains `id_token`), Auth0.js will generate a random `nonce` when you call `webAuth.authorize`, store it in local storage, and pull it out in `webAuth.parseHash`. The default behavior should work in most cases, but some use cases may require a developer to control the `nonce`.
If you want to use a developer generated `nonce`, then you must provide it as an option to both `webAuth.authorize` and `webAuth.parseHash`.
`webAuth.authorize({<Tooltip tip="Nonce: Arbitrary number issued once in an authentication protocol to detect and prevent replay attacks." cta="View Glossary" href="/docs/glossary?term=nonce">nonce</Tooltip>: '1234', responseType: 'token id_token'});
webAuth.parseHash({nonce: '1234'}, callback);`

If you're calling `webAuth.checkSession` instead of `webAuth.authorize`, then you only have to specify your custom `nonce` as an option to `checkSession`:

```js lines theme={null}
webAuth.checkSession({
  nonce: '1234',
}, function (err, authResult) {
    ...
});
```

The `webAuth.checkSession` method will automatically verify that the returned <Tooltip tip="ID Token: Credential meant for the client itself, rather than for accessing a resource." cta="View Glossary" href="/docs/glossary?term=ID+Token">ID Token</Tooltip>'s `nonce` claim is the same as the option.

## Error codes and descriptions

When Auth0.js is used for embedded login, it employs the `/co/authenticate` endpoint, which can produce the following errors:

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Error descriptions are intended to be human readable. The description **should not be parsed by any code** and is subject to change at any time.
</Callout>

| **Status** | **Code**                      | **Description**                                                                                                                                                                  |
| ---------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 400        | invalid\_request              | Invalid request body. All and only of client\_id, credential\_type, username, otp, realm are required.                                                                           |
| 401        | unauthorized\_client          | Cross origin login not allowed.                                                                                                                                                  |
| 400        | unsupported\_credential\_type | Unknown credential type parameter.                                                                                                                                               |
| 400        | invalid\_request              | Unknown realm non-existent-connection.                                                                                                                                           |
| 403        | access\_denied                | Wrong email or password.                                                                                                                                                         |
| 403        | access\_denied                | Authentication error                                                                                                                                                             |
| 403        | blocked\_user                 | Blocked user                                                                                                                                                                     |
| 401        | password\_leaked              | This login attempt has been blocked because the password you're using was previously disclosed through a data breach (not in this application).                                  |
| 429        | too\_many\_attempts           | Your account has been blocked after multiple consecutive login attempts. We've sent you a notification via your preferred contact method with instructions on how to unblock it. |
| 429        | too\_many\_attempts           | We have detected suspicious login behavior and further attempts will be blocked. Please contact the administrator.                                                               |

In addition, you can also get a generic 403 error without an `error` or `error_description` property. The response body would just include something similar to the following:
`Origin https://test.app is not allowed.`

## Logout

To log out a user, use the `logout()` method. This method accepts an options object, which can include the following parameters.

If the `clientID` parameter is included, the `returnTo` URL that is provided must be listed in the Application's **Allowed Logout URLs** in the [Auth0 dashboard](https://manage.auth0.com/#). However, if the `clientID` parameter is not included, the `returnTo` URL must be listed in the **Allowed Logout URLs** at the account level in the [Auth0 dashboard](https://manage.auth0.com/#).

```js lines theme={null}
webAuth.logout({
  returnTo: 'some url here',
  clientID: 'some client ID here'
});
```

## Signup

To sign up a user, use the `signup` method. This method accepts an options object, which can include the following parameters.

| **Parameter**   | **Required** | **Description**                                                                                                                              |
| --------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `email`         | required     | (String) User's email address                                                                                                                |
| `password`      | required     | (String) User's desired password                                                                                                             |
| `username`      | required\*   | (String) User's desired username.  \*Required if you use a database connection and you have enabled **Requires Username**                    |
| `connection`    | required     | (String) The database connection name on your application upon which to attempt user account creation                                        |
| `user_metadata` | optional     | (JSON object) Additional attributes used for user information. Will be stored in [user\_metadata](/docs/manage-users/user-accounts/metadata) |

Signups should be for database connections. Here is an example of the `signup` method and some sample code for a form.

```html lines theme={null}
<h2>Signup Database Connection</h2>
<input class="signup-email" />
<input type="password" class="signup-password" />
<input type="button" class="signup-db" value="Signup!" />
<script type="text/javascript">
    $('.signup-db').click(function (e) {
        e.preventDefault();
        webAuth.signup({
            connection: 'Username-Password-Authentication',
            email: $('.signup-email').val(),
            password: $('.signup-password').val(),
            user_metadata: { plan: 'silver', team_id: 'a111' }
        }, function (err) {
            if (err) return alert('Something went wrong: ' + err.message);
            return alert('success signup without login!')
        });
    });
</script>
```

## Using checkSession to acquire new tokens

The `checkSession` method allows you to acquire a new token from Auth0 for a user who is already authenticated against Auth0 for your domain. The method accepts any valid OAuth2 parameters that would normally be sent to `authorize`. If you omit them, it will use the ones provided when initializing Auth0.

The call to `checkSession` can be used to get a new token for the API that was specified as the <Tooltip tip="Audience: Unique identifier of the audience for an issued token. Named aud in a token, its value contains the ID of either an application (Client ID) for an ID Token or an API (API Identifier) for an Access Token." cta="View Glossary" href="/docs/glossary?term=audience">audience</Tooltip> when `webAuth` was initialized:

```js lines theme={null}
webAuth.checkSession({}, function (err, authResult) {
  // err if automatic parseHash fails
  ...
});
```

See [Extract the AuthResult and Get User Info](#extract-the-authresult-and-get-user-info) for the format of `authResult`.

Or, the token can be acquired for a different API than the one used when initializing `webAuth` by specifying an `audience` and `scope`:

```js lines theme={null}
webAuth.checkSession(
  {
    audience: `https://mydomain/another-api/˜`,
    scope: 'read:messages'
  }, function (err, authResult) {
  // err if automatic parseHash fails
  ...
});
```

Note that `checkSession()` triggers any [rules](/docs/customize/rules) you may have set up, so you should check on your rules in the [Dashboard](https://manage.auth0.com/#/rules) prior to using it.

The actual redirect to `/authorize` happens inside an iframe, so it will not reload your application or redirect away from it.

However, the browser **must** have third-party cookies enabled. Otherwise, **checkSession()** is unable to access the current user's session (making it impossible to obtain a new token without displaying anything to the user). The same will happen if users have [Safari's ITP enabled](https://support.auth0.com/center/s/article/troubleshoot-auth0-token-renewal-issues-in-safari-with-itp-enabled).

Remember to add the URL where the authorization request originates from, to the **Allowed Web Origins** list of your Auth0 application in the [Dashboard](https://manage.auth0.com/#) under your application's **Settings**.

<Warning>
  If the connection is a social connection and you are using Auth0 dev keys, the `checkSession` call will always return `login_required`.
</Warning>

### Polling with checkSession()

In some multi-application scenarios, where Single Logout is desired (a user logging out of one application needs to be logged out of other applications), an application can be set up to periodically poll Auth0 using `checkSession()` to see if a session exists. If the session does not exist, you can then log the user out of the application. The same polling method can be used to implement silent authentication for a Single Sign-on (SSO) scenario.

The poll interval between checks to `checkSession()` should be at least 15 minutes between calls to avoid any issues in the future with rate limiting of this call.

## Password reset requests

If attempting to set up a password reset functionality, you'll use the `changePassword` method and pass in an `options` object, with a `connection` parameter and an `email` parameter.

```js lines theme={null}
$('.change_password').click(function () {
    webAuth.changePassword({
      connection: 'db-conn',
      email:   'foo@bar.com'
    }, function (err, resp) {
      if(err){
        console.log(err.message);
      }else{
        console.log(resp);
      }
    });
  });
```

The user receives an email containing a link to reset their password.

## User management

The Management API provides functionality that allows you to link and unlink separate user accounts from different providers and update user metadata. For more information, read [User Account Linking](/docs/manage-users/user-accounts/user-account-linking).

To get started, you first need to obtain a an <Tooltip tip="Access Token: Authorization credential, in the form of an opaque string or JWT, used to access an API." cta="View Glossary" href="/docs/glossary?term=access+token">access token</Tooltip> that can be used to call the Management API. You can do it by specifying the `https://{yourDomain}/api/v2/` audience when initializing Auth0.js, in which case you will get the access token as part of the authentication flow.

If you use [custom domains](/docs/customize/custom-domains), you will need to instantiate a new copy of `webAuth` using your Auth0 domain rather than your custom one, for use with the Management API calls, as it only works with Auth0 domains.

export const codeExample4 = `var webAuth = new auth0.WebAuth({
  clientID: '{yourClientId}',
  domain: '{yourDomain}',
  redirectUri: 'http://example.com',
  audience: \`https://{yourDomain}/api/v2/\`,
  scope: 'read:current_user',
  responseType: 'token id_token'
});`;

<AuthCodeBlock children={codeExample4} language="js" />

You can also do so by using `checkSession()`:

export const codeExample5 = `webAuth.checkSession(
  {
    audience: \`https://{yourDomain}/api/v2/\`,
    scope: 'read:current_user'
  }, function(err, result) {
     // use result.accessToken
  }
);`;

<AuthCodeBlock children={codeExample5} language="js" />

You must specify the specific scopes you need. You can ask for the following scopes:

* `read:current_user`
* `update:current_user_identities`
* `create:current_user_metadata`
* `update:current_user_metadata`
* `delete:current_user_metadata`
* `create:current_user_device_credentials`
* `delete:current_user_device_credentials`

Once you have the access token, you can create a new `auth0.Management` instance by passing it the account's Auth0 domain, and the access token.

export const codeExample6 = `var auth0Manage = new auth0.Management({
  domain: '{yourDomain}',
  token: 'ACCESS_TOKEN'
});`;

<AuthCodeBlock children={codeExample6} language="js" />

### Get the user profile

To get the user profile data, use the `getUser()` method, with the `userId` and a callback as parameters. The method returns the user profile. Note that the `userID` required here will be the same one fetched from the `client.userInfo` method.
`auth0Manage.getUser(userId, cb);`

### Update the user profile

When updating user metadata, you will need to first create a `userMetadata` object, and then call the `patchUserMetadata` method, passing it the user id and the `userMetadata` object you created. The values in this object will overwrite existing values with the same key, or add new ones for those that don't yet exist in the user metadata. For more information, read [Metadata](/docs/manage-users/user-accounts/metadata).
`auth0Manage.patchUserMetadata(userId, userMetadata, cb);`

### Link users

Linking user accounts will allow a user to authenticate from any of their accounts and no matter which one they use, still pull up the same profile upon login. Auth0 treats all of these accounts as separate profiles by default, so if you wish a user's accounts to be linked, this is the way to go.

The `linkUser` method accepts two parameters, the primary `userId` and the secondary user's ID Token (the token obtained after login with this identity). The user ID in question is the unique identifier for the primary user account. The ID should be passed with the provider prefix, for example, `auth0|1234567890` or `facebook|1234567890`, when using this method. See [User Account Linking](/docs/manage-users/user-accounts/user-account-linking) for details.
`auth0Manage.linkUser(userId, secondaryUserToken, cb);`

After linking the accounts, the second account will no longer exist as a separate entry in the user database, and will only be accessible as part of the primary one.
When accounts are linked, the secondary account's metadata is not merged with the primary account's metadata, and if they are ever unlinked, the secondary account will likewise not retain the primary account's metadata when it becomes separate again.
