Sign in

JavaScript Quickstart

Add authentication to a JavaScript application using MonoCloud.

In this quickstart, you will:

  • Create a MonoCloud Single Page App
  • Install the MonoCloud JavaScript SDK
  • Initialize the client and handle the sign-in and sign-out callbacks
  • Read the authenticated session and add sign-in and sign-out actions

Prerequisites

Before you begin, make sure you have:

  • A MonoCloud account and tenant
  • Node.js 18+ (npm, Yarn, or PNPM)
  • An existing Vite + TypeScript project (or run npm create vite@latest web-js-quickstart -- --template vanilla-ts)
A complete working example is available at: https://github.com/monocloud/web-js-quickstart

Configure MonoCloud

  1. In the MonoCloud Dashboard, create a new Single Page App
  2. Select JavaScript as your stack
  3. Set the following URLs for local development (assuming the Vite default port):
    • Callback URLs: http://localhost:5173
    • Sign-out URLs: http://localhost:5173
    • Cross-Origin URLs: http://localhost:5173
Keep this tab open. You'll need the Domain and Client ID next.

Install the SDK

Install the SDK:

Terminal
npm install @monocloud/auth-web-js

Add the authentication code

Replace src/main.ts with the following. It initializes the client, completes the sign-in / sign-out callbacks on page load, renders the current user, and wires up the buttons.

src/main.ts
import {
  MonoCloudWebJSClient,
  type MonoCloudWebJSClientOptions,
} from "@monocloud/auth-web-js";

const options: MonoCloudWebJSClientOptions = {
  tenantDomain: "https://<your-domain>",
  clientId: "<your-client-id>"
};

const client = new MonoCloudWebJSClient(options);

async function render() {
  const session = await client.getSession();
  const userEl = document.getElementById("user")!;
  userEl.textContent = session
    ? JSON.stringify(session.user, null, 2)
    : "Not signed in";
}

document.getElementById("sign-in")!.addEventListener("click", () => {
  client.signIn();
});

document.getElementById("sign-out")!.addEventListener("click", () => {
  client.signOut();
});

await client.processCallback();
await render();

Add the markup

Replace index.html with the following. The button IDs match the listeners wired up in main.ts.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>MonoCloud JavaScript Quickstart</title>
  </head>
  <body>
    <button id="sign-in">Sign In</button>
    <button id="sign-out">Sign Out</button>
    <pre id="user"></pre>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Run the application

Start the Vite development server:

Terminal
npm run dev

Open http://localhost:5173 and:

  • Click Sign In to authenticate with MonoCloud
  • After redirecting back, the user object renders on the page
  • Click Sign Out to end the session

Your JavaScript application is now authenticated with MonoCloud.

© 2024 MonoCloud. All rights reserved.