Tutorials

Hosted authentication with plain JavaScript

Build a static site that signs users in through OAuth42. The browser SDK handles the OAuth callback, token refresh and live user checks. You need no Next.js, NextAuth or application authentication server.

Your O42 backend must support public browser-client registration and OAuth requests from registered origins.

1. Register a public OAuth application

Have a tenant administrator create an application through the authenticated POST /applications management API with this body. Their setup credential stays outside your app. Copy only the returned client_id into your public configuration.

{
  "name": "My static JavaScript app",
  "redirect_uris": [
    "http://localhost:5173/callback.html",
    "https://your-app.example/callback.html"
  ],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "scopes": ["openid", "profile", "email"],
  "security_settings": { "token_endpoint_auth_method": "none" }
}

The none authentication method explicitly registers a public client. The separate is_public setting controls external-user eligibility; it does not select the client type. Preserve the access, consent and MFA policies appropriate for your application.

Allowed browser origins come from the active application's exact registered redirect URIs. Replace the production hostname, register both environments and use HTTPS outside localhost. Do not add a wildcard, a query string or fragment to a callback. Create a dedicated public registration rather than reusing a confidential Next.js client.

2. Copy the browser bundle into your site

Run these commands in an empty project directory to put the published SDK's browser module in site/.

npm install --ignore-scripts @oauth42/js
mkdir -p site
cp node_modules/@oauth42/js/dist/oauth42.js site/oauth42.js

If you are working from an O42 repository checkout, you can build the same module with npm ci --prefix src/ts/sdk/o42js and npm run build --prefix src/ts/sdk/o42js. Copy src/ts/sdk/o42js/dist/oauth42.js into site/. The checkout also has a complete static example.

In site/config.js, set the issuer and enter the client ID from step 1.

export const config = {
  issuer: 'https://api.oauth42.com',
  clientId: 'YOUR_PUBLIC_CLIENT_ID',
  redirectUri: new URL('./callback.html', window.location.href).href,
};

3. Connect your buttons and callback

Create site/index.html with the sign-in controls and module script.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <title>OAuth42 static sign-in</title>
  </head>
  <body>
    <button id="login">Sign in</button>
    <button id="refresh">Check session</button>
    <button id="logout">Sign out</button>
    <p id="status" role="status">Ready to sign in.</p>
    <pre id="profile" aria-label="Current user"></pre>
    <script type="module" src="./app.js"></script>
  </body>
</html>

Put the login, session check, and sign-out handlers in site/app.js.

import { OAuth42Client } from './oauth42.js';
import { config } from './config.js';

const auth = new OAuth42Client(config);
const status = document.querySelector('#status');
const profile = document.querySelector('#profile');
const showUser = user => {
  profile.textContent = JSON.stringify(user, null, 2);
  status.textContent = 'Signed in as ' + (user.email ?? user.sub);
};
const run = async action => {
  try {
    await action();
  } catch (error) {
    profile.textContent = '';
    status.textContent = error.message;
  }
};

document.querySelector('#login').onclick = () => run(() => auth.login());
document.querySelector('#refresh').onclick = () => run(async () => {
  showUser(await auth.getUser());
});
document.querySelector('#logout').onclick = () => run(async () => {
  profile.textContent = '';
  await auth.logout();
  status.textContent = 'Signed out of this app.';
});

if (location.pathname.endsWith('/callback.html') && location.search) {
  run(async () => showUser(await auth.handleRedirectCallback()));
}

Create a copy of the HTML at the registered callback path before serving the directory.

cp site/index.html site/callback.html
python3 -m http.server 5173 --directory site

Open http://localhost:5173/ and click Sign in. Hosted O42 handles the login UI and policy checks. The SDK validates a single-use state, nonce, S256 PKCE transaction and signed ID token, then removes callback data from the address bar.

getUser() makes a fresh authenticated user-info request to O42. Display its result with textContent; do not treat profile data stored in your UI as authorization for a protected API.

4. Handle expiry, reload and sign-out

Tokens remain in memory. Reloading the page starts without a local session; click Sign in again to use hosted O42 authentication. A five-minute authorization transaction survives the login redirect in sessionStorage. A browser-generated, non-extractable proof key is retained in IndexedDB for that redirect, consumed on callback and then held in memory. Expired pending keys are cleaned up at the next login. Expiring tokens rotate through one refresh request at a time. A failed or ambiguous refresh requires a new login.

Sign out clears this app's memory and revokes its current access token and refresh family. It leaves the hosted O42 sign-in and other applications alone. If server revocation cannot be confirmed, the example displays an explicit error.

  • invalid_state: start a new sign-in; do not reuse an old callback URL.
  • network_error: check connectivity, backend support and the registered callback origin.
  • login_required: the session expired, was revoked or was lost on reload; sign in again.
  • unsupported_policy: the server must issue DPoP-bound public-client tokens. Required PAR and DPoP are supported; confidential-client profiles require a server integration. Do not weaken their policies.

5. Deploy and protect your application

Upload the contents of site/ to your HTTPS static host. Keep callback.html at its registered location. No API route or SPA rewrite is needed. Do not deploy credentials in these assets. Use a restrictive Content Security Policy and minimize third-party scripts; browser tokens cannot be isolated from malicious code already running on your origin.

For your own protected resource server, configure exact resourceUrls and call auth.fetch(url, init). The SDK sends tokens only to those URLs and rejects redirects. Your resource server must validate DPoP proofs, tokens and live authority and supply its own CORS policy (including the DPoP header and nonce response header). O42's browser OAuth CORS policy does not expose its management APIs.

Using Next.js server handlers instead? Follow the Next.js tutorial. Setting sessionStore: 'backend' in that adapter changes token storage, not its server requirement.