Add authentication to a JavaScript application using MonoCloud.
In this quickstart, you will:
Before you begin, make sure you have:
npm create vite@latest web-js-quickstart -- --template vanilla-ts)A complete working example is available at: https://github.com/monocloud/web-js-quickstart
http://localhost:5173http://localhost:5173http://localhost:5173Keep this tab open. You'll need the Domain and Client ID next.
Install the SDK:
npm install @monocloud/auth-web-js
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.
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();
Replace index.html with the following. The button IDs match the listeners wired up in main.ts.
<!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>
Start the Vite development server:
npm run dev
Open http://localhost:5173 and:
Your JavaScript application is now authenticated with MonoCloud.