> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-actions-triggers-prototype.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Details on the Lock v11 API.

# Lock API Reference

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

Lock has many methods, features, and configurable options. This reference is designed to direct you to the ones that you need, and discuss how to use them. Click below to go straight the method you're looking for, or just browse! If you're looking for information about events emitted by Lock, they're listed under the [on()](#on-) method section!

* [new Auth0Lock](#auth0lock) - Instantiating Lock
* [getUserInfo()](#getuserinfo-) - Obtaining the profile of a logged in user
* [show()](#show-) - Showing the Lock widget
* [on()](#on-) - Listening for events
* [resumeAuth()](#resumeauth-) - Use to complete authentication flow when `autoParseHash` is false
* [checkSession()](#checksession-) - Get a new token from Auth0 for an authenticated user
* [logout()](#logout-) - Log out the user

## Auth0Lock

`new Auth0Lock(clientID, domain, options)`

Initializes a new instance of `Auth0Lock` configured with your application's `clientID` and your account's `domain` from your [Auth0](https://manage.auth0.com/#/) management dashboard. The third and optional parameter is an `options` object used to configure Lock for your application's needs. You can find this information at your [application settings](https://manage.auth0.com/#/applications).

* **clientId `{String}`**: Required parameter. Your application's clientId in Auth0.
* **domain `{String}`**: Required parameter. Your Auth0 domain. Usually your-account.auth0.com.
* **options `{Object}`**: Optional parameter. Allows for the configuration of Lock's appearance and behavior. See [the configuration options page](/docs/libraries/lock/lock-configuration) for details.

export const codeExample1 = `var Auth = (function() {

  var privateStore = {};

  function Auth() {
    // Instantiate Lock - without custom options
    this.lock = new Auth0Lock(
      '<{yourClientId}>',
      '<{yourDomain}>'
    );
  }

  Auth.prototype.getProfile = function() {
    return privateStore.profile;
  };

  Auth.prototype.authn = function() {
    // Listening for the authenticated event and get profile
    this.lock.on("authenticated", function(authResult) {
      // Use the token in authResult to getUserInfo() and save it if necessary
      this.getUserInfo(authResult.accessToken, function(error, profile) {
        if (error) {
          // Handle error
          return;
        }

        //save Access Token only if necessary
        privateStore.accessToken = accessToken;
        privateStore.profile = profile;

        // Update DOM
      });
    });
  };
  return Auth;
}());`;

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

## getUserInfo()

`getUserInfo(accessToken, callback)`

Once the user has logged in and you are in possession of a token, you can use that token to obtain the user's profile with `getUserInfo`. This method replaces the deprecated `getProfile()`.

* **accessToken \{String}**: User token.
* **callback \{Function}**: Will be invoked after the user profile been retrieved.

```js lines theme={null}
lock.getUserInfo(accessToken, function(error, profile) {
  if (!error) {
    alert("hello " + profile.name);
  }
});
```

## show()

`show(options)`

The `show` method displays the widget. Beginning with Lock version 10.2.0, the `show` method can now accept an `options` object as a parameter. Note that this parameter is meant to be used as a way to override your Lock's `options` for this particular displaying of the widget - options should be set when instantiating Lock, and overridden, only if needed for your specific use case, here.

The following subset of `options` to be overridden from the values they were given (or their defaults) when Lock was instantiated:

* allowedConnections
* auth.params
* allowLogin
* allowSignUp
* allowForgotPassword
* initialScreen
* rememberLastLogin

For more detail on the entire list of configurable options that can be chosen when instantiating Lock, as opposed to the limited subset above that can be overridden in the `show` method, please see the [user configurable options page](/docs/libraries/lock/lock-configuration).

Options override examples:

```js lines theme={null}
// Show the Lock widget, without overriding any options
lock.show();

// Show the Lock widget, overriding some options
lock.show({
  allowedConnections: ["twitter", "facebook"],
  allowSignUp: false
});
```

Options should be set when first instantiating Lock `var lock = new Auth0Lock(clientId, domain, options);`. Options should only be passed to `show` in order to override your previously set options while displaying the widget at this particular time and place.

There is an additional option that can be set in the `show` method called `flashMessage`.

### flashMessage

This object is only available as an option for the `show` method, not for use in the normal `options` object when instantiating Lock. The `flashMessage` object shows an error or success flash message when Lock is shown. It has the following parameters:

* **type** \{String}: The message type, it should be either `error` or `success`.
* **text** \{String}: The text to show.

```js lines theme={null}
lock.show({
  flashMessage:{
    type: 'success',
    text: 'Amazing Success!!'
  }
});
```

A practical application of the `flashMessage` option is to handle authorization errors. The `flashMessage` can be populated with error description text.

```js lines theme={null}
lock.on('authorization_error', function(error) {
  lock.show({
    flashMessage: {
      type: 'error',
      text: error.errorDescription
    }
  });
});
```

So, if `tester@example.com` were now to try to sign in, being a user who is blocked, the user will be shown Lock again, with a top bar displaying the error message, rather than simply failing to login and Lock closing.

## hide()

`hide()`

The `hide` method closes the widget if it is currently open. The widget closes itself under most circumstances, so this method would primarily be invoked in specific use cases only. For instance, one might wish to listen for the `unrecoverable_error` event and then `hide` the Lock and redirect to their own custom error page. Another example is users who are implementing [popup mode](/docs/libraries/lock/lock-authentication-modes), and might need to manually `hide` the widget after the `authenticated` event fires.

Example usage to hide (close) the Lock widget in popup mode:

```js lines theme={null}
// Listen for authenticated event and hide Lock
lock.on("authenticated", function() {
  lock.hide();

  // Whatever else you'd like to do on authenticated event

});
```

## on()

Lock will emit events during its lifecycle. The `on` method can be used to listen for particular events and react to them.

* `show`: emitted when Lock is shown. Has no arguments.
* `hide`: emitted when Lock is hidden. Has no arguments.
* `unrecoverable_error`: emitted when there is an unrecoverable error, for instance when no connection is available. Has the error as the only argument.
* `authenticated`: emitted after a successful authentication. Has the authentication result as the only argument. The authentication result contains the token which can be used to get the user's profile or stored to log them in on subsequent checks.
* `authorization_error`: emitted when authorization fails. Has error as the only argument.
* `hash_parsed`: every time a new Auth0Lock object is initialized in redirect mode (the default), it will attempt to parse the hash part of the url looking for the result of a login attempt. This is a low level event for advanced use cases and `authenticated` and `authorization_error` should be preferred when possible. After that this event will be emitted with `null` if it couldn't find anything in the hash. It will be emitted with the same argument as the `authenticated` event after a successful login or with the same argument as `authorization_error` if something went wrong. This event won't be emitted in [popup mode](/docs/libraries/lock/lock-authentication-modes) because there is no need to parse the url's hash part.
* `forgot_password ready`: emitted when the "Forgot password" screen is shown. (Only in Version >`10.18`)
* `forgot_password submit`: emitted when the user clicks on the submit button of the "Forgot password" screen. (Only in Version >`10.14`)
* `signin ready`: emitted when the "Sign in" screen is shown.
* `signup ready`: emitted when the "Sign up" screen is shown.
* `signin submit`: emitted when the user clicks on the submit button of the "Login" screen. (Only in Version >`10.18`)
* `signup submit`: emitted when the user clicks on the submit button of the "Sign Up" screen. (Only in Version >`10.18`)
* `federated login`: emitted when the user clicks on a social connection button. Has the connection name and the strategy as arguments. (Only in Version >`10.18`)
* `socialOrPhoneNumber ready`: emitted when the <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> screen with Social + Phone Number is shown
* `socialOrPhoneNumber submit`: emitted when the Passwordless screen with Social + Phone Number is submitted
* `socialOrEmail ready`: emitted when the Passwordless screen with Social + Email is shown
* `socialOrEmail submit`: emitted when the Passwordless screen with Social + Email is submitted
* `vcode ready`: emitted when the Passwordless screen with the one-time-password is shown
* `vcode submit`: emitted when the Passwordless screen with the one-time-password is submitted

The `authenticated` event listener has a single argument, an `authResult` object. This object contains the following properties: `accessToken`, `idToken`, `state`, `refreshToken` and `idTokenPayload`.

An example use of the `authenticated` event:

export const codeExample2 = `var Auth = (function() {

  var privateStore = {};

  function Auth() {
    this.lock = new Auth0Lock(
      '<{yourClientId}>',
      '<{yourDomain}>'
    );
  }

  Auth.prototype.getProfile = function() {
    return privateStore.profile;
  };

  Auth.prototype.authn = function() {
    // Listening for the authenticated event
    this.lock.on("authenticated", function(authResult) {
      // Use the token in authResult to getUserInfo() and save it if necessary
      this.getUserInfo(authResult.accessToken, function(error, profile) {
        if (error) {
          // Handle error
          return;
        }

        privateStore.profile = profile;

      });
    });
  };
  return Auth;
}());`;

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

## resumeAuth()

This method can only be used when you set the [auth.autoParseHash](/docs/libraries/lock/lock-configuration) option to `false`. You'll need to call `resumeAuth` to complete the authentication flow. This method is useful when you're using a client-side router that uses a `#` to handle urls (angular2 with `useHash`, or react-router with `hashHistory`).

* **hash** \{String}: The hash fragment received from the redirect.
* **callback** \{Function}: Will be invoked after the parse is done. Has an error (if any) as the first argument and the authentication result as the second one. If there is no hash available, both arguments will be `null`.

```js lines theme={null}
lock.resumeAuth(hash, function(error, authResult) {
  if (error) {
    alert("Could not parse hash");
  }
  //This is just an example; you should not log Access Tokens in production.
  console.log(authResult.accessToken);
});
```

## checkSession()

The `checkSession` method allows you to acquire a new token from Auth0 for a user who is already authenticated against Auth0 for your domain. It takes the following parameters:

* **options** \{Object}: Optional. 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.
* **callback** \{Function}: Will be invoked with the token renewal result. Has an error (if any) as the first argument and the authentication result as the second one.

```js lines theme={null}
lock.checkSession({}, function(err, authResult) {
  // handle error or new tokens
});
```

## logout()

Logs out the user.

* **options** \{Object}: This is optional and follows the same rules as auth0.js logout().

```js lines theme={null}
lock.logout({
  returnTo: 'https://myapp.com/bye-bye'
});
```
