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

# Add Login to Your JavaScript Application

export const SignUpForm = () => {
  return <div className="flex flex-col gap-2 items-center h-full">
      <img noZoom src="/docs/img/quickstarts/action_hero_dashboard.svg" alt="Sign up for an Auth0 account" style={{
    width: "250px",
    height: "250px"
  }} />
      <span className="text-center" style={{
    width: "400px"
  }}>
        Sign up for an{" "}
        <a href="https://auth0.com/signup" target="_blank" rel="noopener noreferrer">
          Auth0 account
        </a>{" "}
        or{" "}
        <span className="font-semibold text-primary cursor-pointer" onClick={() => console.log("log in")}>
          log in
        </span>{" "}
        to your existing account to integrate directly with your own tenant.
      </span>
      <button onClick={() => console.log("sign up")} className="bg-primary dark:bg-primary-light text-white px-4 py-2 rounded-md mt-4 font-medium" style={{
    width: "140px"
  }}>
        Sign up
      </button>
    </div>;
};

export const SideMenuSectionItem = ({id, children}) => {
  return <div id={`side-menu-item-${id}`} className="recipe-side-menu-item flex flex-col w-full h-full">
      {children}
    </div>;
};

export const SideMenu = ({sections, children}) => {
  const [visibleSection, setVisibleSection] = useState(sections[0]?.id ?? null);
  const checkVisibility = () => {
    let currentVisible = null;
    const viewportHeight = window.innerHeight;
    const scrollY = window.scrollY;
    sections.forEach(({id}) => {
      const section = document.getElementById(id);
      if (section) {
        const rect = section.getBoundingClientRect();
        const sectionTop = rect.top + scrollY;
        const sectionBottom = sectionTop + rect.height;
        const multiplier = viewportHeight > 1600 ? 0.34 : 0.22;
        if (scrollY + viewportHeight * multiplier >= sectionTop && scrollY <= sectionBottom) {
          currentVisible = id;
        }
      }
    });
    if (currentVisible && currentVisible !== visibleSection) {
      setVisibleSection(currentVisible);
    }
  };
  useEffect(() => {
    const throttledCheck = () => {
      setTimeout(checkVisibility, 100);
    };
    checkVisibility();
    window.addEventListener("scroll", throttledCheck);
    return () => {
      window.removeEventListener("scroll", throttledCheck);
    };
  }, [sections, visibleSection]);
  useEffect(() => {
    sections.forEach(({id}) => {
      const section = document.getElementById(id);
      const sideMenuItem = document.getElementById(`side-menu-item-${id}`);
      if (section) {
        if (id === visibleSection) {
          section.classList.add("active-section");
        } else {
          section.classList.remove("active-section");
        }
      }
      if (sideMenuItem) {
        if (id === visibleSection) {
          sideMenuItem.classList.add("active-side-menu-item");
        } else {
          sideMenuItem.classList.remove("active-side-menu-item");
        }
      }
    });
  }, [visibleSection, sections]);
  return <div className="recipe-side-menu sticky px-2 py-1" style={{
    height: "calc(100vh - 7rem)",
    top: "7rem",
    scrollMarginTop: "var(--scroll-mt)"
  }}>
      {children.map(child => {
    if (child.props.id === visibleSection) {
      return child;
    }
    return null;
  })}
    </div>;
};

export const Section = ({id, title, stepNumber, children, isSingleColumn = false}) => {
  return <div id={id} className={`recipe-section flex flex-col transition-opacity duration-200 ${isSingleColumn ? "opacity-100 dark:opacity-100" : "opacity-60 dark:opacity-60"}`}>
      <Step title={title} stepNumber={stepNumber} titleSize="h3">
        {children}
      </Step>
    </div>;
};

export const Content = ({title, children}) => {
  return <div className="recipe-content flex flex-col">
      {title && <h1 className="text-3xl">{title}</h1>}
      {children}
    </div>;
};

export const Recipe = ({children, isSingleColumn = false}) => {
  return <div className={`pl-4 recipe-container mx-auto grid grid-cols-1 gap-10 relative ${isSingleColumn ? "md:grid-cols-1" : "md:grid-cols-2"}`}>
      {children}
    </div>;
};

export const sections = [{
  id: "configure-auth0",
  title: "Configure Auth0"
}, {
  id: "add-the-auth0-spa-sdk",
  title: "Add the Auth0 SPA SDK"
}, {
  id: "create-the-auth0-client",
  title: "Create the Auth0 client"
}, {
  id: "add-login-to-your-application",
  title: "Add login to your application"
}, {
  id: "handle-the-callback-from-auth0",
  title: "Handle the callback from Auth0"
}, {
  id: "add-logout-to-your-application",
  title: "Add logout to your application"
}, {
  id: "show-user-profile-information",
  title: "Show user profile information"
}];

<Recipe>
  <Content>
    Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to
    integrate Auth0, add authentication, and display user profile information in a Single-Page Application (SPA) that
    uses plain JavaScript, using the [Auth0 SPA SDK](https://github.com/auth0/auth0-spa-js).

    To use this quickstart, you’ll need to:

    * Sign up for a free Auth0 account or log in to Auth0.
    * Have a working project that you want to integrate with. Alternatively, you can view or download a sample application after logging in.

    <Callout icon="file-lines" iconType="regular">
      This quickstart assumes you are adding Auth0 to a plain JavaScript application, as opposed to using a
      framework such as React or Angular.
    </Callout>

    <Section id={sections[0].id} title={sections[0].title} stepNumber="1">
      To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is
      where you will configure how you want authentication to work for the project you are developing.

      ### Configure an application

      Use the interactive selector to create a new Auth0 application or select an existing application that represents
      the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID
      that your application code will use to call Auth0 APIs through the SDK.

      Any settings you configure using this quickstart will automatically update for your Application in the [Dashboard](https://manage.auth0.com/#/), which is where you
      can manage your Applications in the future.

      If you would rather explore a complete configuration, you can view a sample application instead.

      ### Configure Callback URLs

      A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have
      authenticated. If not set, users will not be returned to your application after they log in.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:3000`.
      </Callout>

      ### Configure Logout URLs

      A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged
      out. If not set, users will not be able to log out from your application and will receive an error.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:3000`.
      </Callout>

      ### Configure Allowed Web Origins

      An Allowed Web Origin is a URL that you want to be allowed to access to your authentication flow. This must
      contain the URL of your project. If not properly set, your project will be unable to silently refresh
      authentication tokens, so your users will be logged out the next time they visit your application or refresh a
      page.

      <Callout icon="file-lines" iconType="regular">
        If you are following along with our sample project, set this to `http://localhost:3000`.
      </Callout>
    </Section>

    <Section id={sections[1].id} title={sections[1].title} stepNumber="2">
      Auth0 provides a SPA SDK (auth0-spa-js) to simplify the process of implementing Auth0 authentication and
      authorization in JavaScript applications. You can install the Auth0 SPA SDK as an NPM package or from the CDN. For
      the purpose of this quickstart, we will use the CDN. Include this script tag on your HTML page:

      ```html theme={null}
      <script src="https://cdn.auth0.com/js/auth0-spa-js/2.0/auth0-spa-js.production.js"></script>
      ```
    </Section>

    <Section id={sections[2].id} title={sections[2].title} stepNumber="3">
      Create a new instance of the Auth0 client provided by the Auth0 SPA SDK and provide the Auth0 application details
      you created earlier in this quickstart.

      If a user has previously logged in, the client will refresh the authentication state on page load; the user will
      still be logged in once the page is refreshed.
    </Section>

    <Section id={sections[3].id} title={sections[3].title} stepNumber="4">
      Now that you have configured your Auth0 Application, added the Auth0 SPA SDK, and created the Auth0 client, you
      need to set up login for your project. To do this, you will use the SDK’s `loginWithRedirect()` method
      to redirect users to the Auth0 Universal Login page where Auth0 can authenticate them. After a user successfully
      authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.

      Create a login button in your application that calls `loginWithRedirect()` when selected.

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to log in to your application.

        Run your application, and select the login button. Verify that:

        * you can log in or sign up using a username and password
        * your application redirects you to the [Auth0 Universal Login](/universal-login) page
        * you are redirected to Auth0 for authentication
        * Auth0 successfully redirects back to your application after authentication
        * you do not receive any errors in the console related to Auth0
      </Callout>
    </Section>

    <Section id={sections[4].id} title={sections[4].title} stepNumber="5">
      When the browser is redirected back to your application process, your application should call the
      `handleRedirectCallback()` function on the Auth0 client only when it detects a callback from Auth0. One
      way to do this is to only call `handleRedirectCallback()` when `code` and `state`
      query parameters are detected.

      If handling the callback was successful, the parameters should be removed from the URL so the callback handler
      will not be triggered the next time the page loads.

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        Your callback from Auth0 should now be properly handled.

        Run your application, and select the login button again. Verify that:

        * Auth0 successfully redirects back to your application after authentication.
        * the query parameters are removed from the URL.
      </Callout>
    </Section>

    <Section id={sections[5].id} title={sections[5].title} stepNumber="6">
      Users who log in to your project will also need [a way to log out](/docs/logout/guides/logout-auth0). The Auth0 client provides a `logout()` method that you can use
      to log a user out of your app. When users log out, they will be redirected to your [Auth0 logout endpoint](/docs/api/authentication?javascript#logout),
      which will then immediately redirect them to your application and the logout URL you set up earlier in this
      quickstart.

      Create a logout button in your application that calls `logout()` when selected.

      <Callout icon="file-lines" iconType="regular">
        The SDK exposes an `isAuthenticated()` function that allows you to check whether a user is
        authenticated or not. You can render the login and logout buttons conditionally based on the value of
        the `isAuthenticated()` function. Alternatively, you can use a single button to combine both
        login and logout buttons as well as their conditional rendering.
      </Callout>

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to log out of your application.

        Run your application, log in, and select the logout button. Verify that:

        * you are redirected to Auth0's logout endpoint.
        * Auth0 successfully redirects back to your application and the correct logout URL.
        * you are no longer logged in to your application.
        * you do not receive any errors in the console related to Auth0.
      </Callout>
    </Section>

    <Section id={sections[6].id} title={sections[6].title} stepNumber="7">
      Now that your users can log in and log out, you will likely want to be able to retrieve the [profile information](/docs/users/concepts/overview-user-profile)
      associated with authenticated users. For example, you may want to be able to personalize the user interface by
      displaying a logged-in user’s name or profile picture.

      The Auth0 SPA SDK provides user information through the `getUser()` function exposed by the Auth0
      client. The Auth0 client also exposes an `isAuthenticated()` function that allows you to check whether
      a user is authenticated or not, which you can use to determine whether to show or hide UI elements, for example.
      Review the code in the interactive panel to see examples of how to use these functions.

      <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
        ##### Checkpoint

        You should now be able to view user profile information.

        Run your application, and verify that:

        * user information displays correctly after you have logged in.
        * user information does not display after you have logged out.
      </Callout>
    </Section>

    ## Next Steps

    Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.<br /><br />

    This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

    * [Auth0 Dashboard](https://manage.auth0.com/dashboard/us/dev-s3674bdouue0bd73) - Learn how to configure and manage your Auth0 tenant and applications
    * [auth0-flutter SDK](https://www.github.com/auth0/auth0-flutter/) - Explore the SDK used in this tutorial more fully
    * [Auth0 Marketplace](https://marketplace.auth0.com/) - Discover integrations you can enable to extend Auth0’s functionality
  </Content>

  <SideMenu sections={sections}>
    <SideMenuSectionItem id={sections[0].id}>
      <SignUpForm />
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[1].id}>
      <SignUpForm />
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[2].id}>
      ```js app.js highlight={1-7} lines theme={null}
      auth0.createAuth0Client({
        domain: "dev-s3674bdouue0bd73.us.auth0.com",
        clientId: "QqpqsvIQHjLodaUIPpabJcIHoG41tbAv",
        authorizationParams: {
          redirect_uri: window.location.origin
        }
      }).then(async (auth0Client) => {
        // Assumes a button with id "login" in the DOM
        const loginButton = document.getElementById("login");

        loginButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.loginWithRedirect();
        });

        if (location.search.includes("state=") && 
            (location.search.includes("code=") || 
            location.search.includes("error="))) {
          await auth0Client.handleRedirectCallback();
          window.history.replaceState({}, document.title, "/");
        }

        // Assumes a button with id "logout" in the DOM
        const logoutButton = document.getElementById("logout");

        logoutButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.logout();
        });

        const isAuthenticated = await auth0Client.isAuthenticated();
        const userProfile = await auth0Client.getUser();

        // Assumes an element with id "profile" in the DOM
        const profileElement = document.getElementById("profile");

        if (isAuthenticated) {
          profileElement.style.display = "block";
          profileElement.innerHTML = `
                  <p>${userProfile.name}</p>
                  <img src="${userProfile.picture}" />
                `;
        } else {
          profileElement.style.display = "none";
        }
      });
      ```
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[3].id}>
      ```js app.js highlight={8-14} lines theme={null}
      auth0.createAuth0Client({
        domain: "dev-s3674bdouue0bd73.us.auth0.com",
        clientId: "QqpqsvIQHjLodaUIPpabJcIHoG41tbAv",
        authorizationParams: {
          redirect_uri: window.location.origin
        }
      }).then(async (auth0Client) => {
        // Assumes a button with id "login" in the DOM
        const loginButton = document.getElementById("login");

        loginButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.loginWithRedirect();
        });

        if (location.search.includes("state=") && 
            (location.search.includes("code=") || 
            location.search.includes("error="))) {
          await auth0Client.handleRedirectCallback();
          window.history.replaceState({}, document.title, "/");
        }

        // Assumes a button with id "logout" in the DOM
        const logoutButton = document.getElementById("logout");

        logoutButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.logout();
        });

        const isAuthenticated = await auth0Client.isAuthenticated();
        const userProfile = await auth0Client.getUser();

        // Assumes an element with id "profile" in the DOM
        const profileElement = document.getElementById("profile");

        if (isAuthenticated) {
          profileElement.style.display = "block";
          profileElement.innerHTML = `
                  <p>${userProfile.name}</p>
                  <img src="${userProfile.picture}" />
                `;
        } else {
          profileElement.style.display = "none";
        }
      });
      ```
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[4].id}>
      ```js app.js highlight={16-21} lines theme={null}
      auth0.createAuth0Client({
        domain: "dev-s3674bdouue0bd73.us.auth0.com",
        clientId: "QqpqsvIQHjLodaUIPpabJcIHoG41tbAv",
        authorizationParams: {
          redirect_uri: window.location.origin
        }
      }).then(async (auth0Client) => {
        // Assumes a button with id "login" in the DOM
        const loginButton = document.getElementById("login");

        loginButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.loginWithRedirect();
        });

        if (location.search.includes("state=") && 
            (location.search.includes("code=") || 
            location.search.includes("error="))) {
          await auth0Client.handleRedirectCallback();
          window.history.replaceState({}, document.title, "/");
        }

        // Assumes a button with id "logout" in the DOM
        const logoutButton = document.getElementById("logout");

        logoutButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.logout();
        });

        const isAuthenticated = await auth0Client.isAuthenticated();
        const userProfile = await auth0Client.getUser();

        // Assumes an element with id "profile" in the DOM
        const profileElement = document.getElementById("profile");

        if (isAuthenticated) {
          profileElement.style.display = "block";
          profileElement.innerHTML = `
                  <p>${userProfile.name}</p>
                  <img src="${userProfile.picture}" />
                `;
        } else {
          profileElement.style.display = "none";
        }
      });
      ```
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[5].id}>
      ```js app.js highlight={23-29} lines theme={null}
      auth0.createAuth0Client({
        domain: "dev-s3674bdouue0bd73.us.auth0.com",
        clientId: "QqpqsvIQHjLodaUIPpabJcIHoG41tbAv",
        authorizationParams: {
          redirect_uri: window.location.origin
        }
      }).then(async (auth0Client) => {
        // Assumes a button with id "login" in the DOM
        const loginButton = document.getElementById("login");

        loginButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.loginWithRedirect();
        });

        if (location.search.includes("state=") && 
            (location.search.includes("code=") || 
            location.search.includes("error="))) {
          await auth0Client.handleRedirectCallback();
          window.history.replaceState({}, document.title, "/");
        }

        // Assumes a button with id "logout" in the DOM
        const logoutButton = document.getElementById("logout");

        logoutButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.logout();
        });

        const isAuthenticated = await auth0Client.isAuthenticated();
        const userProfile = await auth0Client.getUser();

        // Assumes an element with id "profile" in the DOM
        const profileElement = document.getElementById("profile");

        if (isAuthenticated) {
          profileElement.style.display = "block";
          profileElement.innerHTML = `
                  <p>${userProfile.name}</p>
                  <img src="${userProfile.picture}" />
                `;
        } else {
          profileElement.style.display = "none";
        }
      });
      ```
    </SideMenuSectionItem>

    <SideMenuSectionItem id={sections[6].id}>
      ```js app.js highlight={31-45} lines theme={null}
      auth0.createAuth0Client({
        domain: "dev-s3674bdouue0bd73.us.auth0.com",
        clientId: "QqpqsvIQHjLodaUIPpabJcIHoG41tbAv",
        authorizationParams: {
          redirect_uri: window.location.origin
        }
      }).then(async (auth0Client) => {
        // Assumes a button with id "login" in the DOM
        const loginButton = document.getElementById("login");

        loginButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.loginWithRedirect();
        });

        if (location.search.includes("state=") && 
            (location.search.includes("code=") || 
            location.search.includes("error="))) {
          await auth0Client.handleRedirectCallback();
          window.history.replaceState({}, document.title, "/");
        }

        // Assumes a button with id "logout" in the DOM
        const logoutButton = document.getElementById("logout");

        logoutButton.addEventListener("click", (e) => {
          e.preventDefault();
          auth0Client.logout();
        });

        const isAuthenticated = await auth0Client.isAuthenticated();
        const userProfile = await auth0Client.getUser();

        // Assumes an element with id "profile" in the DOM
        const profileElement = document.getElementById("profile");

        if (isAuthenticated) {
          profileElement.style.display = "block";
          profileElement.innerHTML = `
                  <p>${userProfile.name}</p>
                  <img src="${userProfile.picture}" />
                `;
        } else {
          profileElement.style.display = "none";
        }
      });
      ```
    </SideMenuSectionItem>
  </SideMenu>
</Recipe>
