JavaScript Quickstart
Add OAuth2/OIDC authentication to a vanilla JavaScript single-page 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
- In the MonoCloud Dashboard, create a new Single Page App
- Select JavaScript as your stack
- 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
- Callback URLs:
Keep this tab open. You'll need the Domain and Client ID next.
Install the SDK
Install the SDK:
npm install @monocloud/auth-web-jsAdd 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.
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.
<!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:
npm run devOpen 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.