Browser app
In the wizard: No API that Otoko Identity calls · Web app, no server code at sign-in
A single-page app (SPA) with no server of its own, such as React, Vue or Angular served as static files. It signs people in from the browser with PKCE, so it holds no secret. Otoko Identity (OI) runs sign-up, forgot password and invitations on its own pages, and you manage roles in OI's console. For a new app with a server, signing in from the server is recommended: see Which kind of app?.
What you'll build
- A Sign in button that sends people to OI's sign-in page, which also has Register and Forgot password.
- A
/callbackroute, where OI sends people back and the app swaps the code for tokens. - A front page with the signed-in person's name, email and roles, and a Sign out button.
It uses oidc-client-ts, an OpenID Connect library for the browser, in every framework.
Trying it with Otoko Identity on your own machine?
The examples use https://identity.example.com for Otoko Identity. With OI running locally in Docker, its address is http://localhost:8001 and the console is at http://localhost:3100/admin. Your app runs on localhost as usual.
With a coding agent
To have Claude Code, Cursor or another coding agent do these steps in your project, paste it this prompt. Check what it writes against the steps below.
Paste this into your coding agent, in your single-page app's project. It tells you what to register on the console, then writes sign-in, the callback and sign-out in the browser with oidc-client-ts, with no backend.
Show the full prompt
Connect this browser app's sign-in to Otoko Identity
You are connecting the sign-in of the single-page app (SPA) you're working in to Otoko Identity (OI), a standard OpenID Connect provider. The app has no server or backend of its own: it signs people in from the browser with PKCE, and holds no secret. Work through the steps below in order, and stop where a step says to wait for the person.
Scope
- A Sign in button that sends people to OI, a
/callbackroute where the app swaps the code for tokens, a front page with the signed-in person's name, email and roles, and a Sign out button. - OI runs sign-up, forgot password and invitations on its own pages, and roles are managed on OI's console. Don't build them.
- Change nothing unrelated to signing in.
Rules
- A browser app has no secrets. Never put a client secret, an API key or a webhook secret in it: anything in the page can be read.
- Use oidc-client-ts, the OpenID Connect library this setup is written for, in any framework. Never write the flow by hand.
- Keep the tokens where oidc-client-ts puts them, in sessionStorage. Never move them to localStorage.
- Use https everywhere outside a local machine.
1. Look at the project
- Find its framework (React, Vue and Angular are the worked examples; Svelte, Solid, a static Next.js export or plain JavaScript take the same steps), its router, its dev address and port (Vite's is
http://localhost:5173, Angular'shttp://localhost:4200), and any sign-in it already has. - Confirm with the person that it has no backend at all. If it calls an API of theirs, stop and send them to the prompt on https://identity-docs.otoko.com/quickstarts/browser-app-with-api. If its own server renders the pages, send them to https://identity-docs.otoko.com/quickstarts/server-rendered-app.
2. Tell the person what to register, then wait
The app is registered on OI's console; you can't do this part. Tell the person to open https://identity.otoko.com/admin/apps/new and:
- Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer No.
- How people sign in: choose Web app, and to Does your app run server code when someone signs in? answer No. Type the App address, the dev address you found. Open Advanced and change the Sign-in return address to the app address plus
/callback, such ashttp://localhost:5173/callback. Leave the Sign-out return address as the front page. - Email: leave Send this app's emails through Otoko Identity's mail server ticked, with an optional Reply-to address. Only for an app with its own mail server, untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat.
- Choose Create, then on Connect your app the Frontend section's Copy all. A browser app never uses the Server section's API key, or any other value outside Frontend: leave them out.
- Turn on sign-up: a new client starts with it off. Open Apps, the app, the Clients tab and the client, turn on Allow sign-up, and choose Save client.
- Add a role: on the app's Users & roles tab, set Roles managed by to Admin console, choose Add role, type
member, and choose Save changes.
Ask them to tell you when it's done, and to give you the Frontend section's values, none of which is secret: IDENTITY_ISSUER, IDENTITY_CLIENT_ID, IDENTITY_REDIRECT_URI and IDENTITY_SCOPES. Wait.
3. Settings
The settings are built into the page. Add roles to the scopes, so the app can read roles.
- Vite (React, Vue):
.env.local, with.env.examplebeside it, holdingVITE_IDENTITY_ISSUER,VITE_IDENTITY_CLIENT_ID,VITE_IDENTITY_REDIRECT_URIandVITE_IDENTITY_SCOPES(such asopenid profile email roles). Vite builds only names that start withVITE_into the page. - Angular:
src/environments/environment.ts, withidentity: { issuer, clientId, redirectUri, scopes }. - Another stack: the same four values, with its own public prefix, such as
NEXT_PUBLIC_.
4. Install
npm install oidc-client-ts, plus a router if the project has none:react-router-domfor React,vue-routerfor Vue. Angular has its own.
5. The code
The connection to OI, one module everything imports from, such as src/auth/oidc.ts (Angular: an AuthService in src/app/auth/auth.service.ts):
- A
UserManagerwithauthorityset to the issuer (it reads OI's discovery document itself),client_id,redirect_uri,post_logout_redirect_uriset to the app's origin plus/,scope,loadUserInfo: true(name, email and roles come from OI's userinfo endpoint), andautomaticSilentRenew: false. signIn()callssigninRedirect({ nonce: crypto.randomUUID() }). The library uses the code flow with PKCE (S256) and a state.signOut()callssignoutRedirect(), which sends the ID token asid_token_hint, so OI ends its own session too and returns the browser to the front page.
The signed-in person, shared by every component (a React context and provider, a Vue composable, the Angular service): read getUser() at start, treat an expired user as signed out, and follow the userLoaded, userUnloaded and accessTokenExpired events.
The /callback route:
- Call
signinRedirectCallback()once (React runs effects twice in development, and a code works only once), then go to/withreplace, so the used code leaves the address and the history. - On an error, go to
/if someone is already signed in (a reload or Back on a used callback), and otherwise show the error with a Try again button that callssignIn().
The front page:
- Signed out: a Sign in button.
- Signed in:
Hello,and the name (or the email), the email,Roles:and the roles fromprofile.roles(ornone), and a Sign out button.
6. Check it works
Run the app (npm run dev, or npm start for Angular) and open it. You can't sign in for the person, so ask them to:
- Choose Sign in, then Register on OI's page, and type the code OI emails. They're back on the front page, signed in, with their name and email.
- In the console, give themselves the
memberrole, then sign out and in again. The page says Roles: member. - Choose Sign out, then Sign in again. OI asks for their email: its own session ended too.
- In the browser's developer tools, under Application, find the tokens in Session storage, and nothing in Local storage.
If OI answers invalid_redirect_uri, the redirect setting and the client's Valid redirect URIs differ. If the browser shows a CORS error from OI, the page's address isn't the origin of one of those redirect addresses. For other errors, read https://identity-docs.otoko.com/troubleshooting.
Finish with a short report: the files you changed, the routes you added, the settings the code reads (by name), and anything the person still has to do, such as adding the live addresses to the client before going live.
More detail
- https://identity-docs.otoko.com/quickstarts/browser-app: this setup, step by step, with React, Vue and Angular code.
- https://identity-docs.otoko.com/api-reference/openid-connect: the flow, endpoints and scopes.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
Register the app
-
In the console, open Connect an app.
-
Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer No.
-
How people sign in: choose Web app, and to Does your app run server code when someone signs in? answer No. Type the App address, such as
http://localhost:5173(Vite) orhttp://localhost:4200(Angular). Open Advanced and change the Sign-in return address to the app address plus/callback, such ashttp://localhost:5173/callback. Leave the Sign-out return address as the front page. -
Email:
Otoko Identity emails sign-up codes, forgot-password codes and invitations. Leave Send this app's emails through Otoko Identity's mail server ticked, and the app needs no mail server of its own; a Reply-to address is optional. Only if your app has its own mail server, untick it, type the From address OI sends from, and fill in the Mail server section that appears: host, port, encryption, username and password, the last two together, and its timeouts. It's saved when the app is made, and the last step offers Send test email.
-
Choose Create. On Connect your app, choose the Frontend section's Copy all. A browser app never uses the Server section's API key, so leave it out.
-
Turn on sign-up. A new client starts with it off, and until it's on, OI's sign-in page shows no Register link. Open Apps, your app, the Clients tab, and your client. Turn on Allow sign-up, then choose Save client. (The app's own Sign-up allowed and Forgot password, under Login on its Overview tab, are on for a new app.)
-
Add a role. On the app's Users & roles tab, set Roles managed by to Admin console (an app with a backend starts on Application backend), choose Add role, type
member, and choose Save changes. Once someone has signed up, give them the role with the pencil button in their Roles column in the users list. Your app asks for therolesscope to read them.
Settings
The settings go into the page when it's built. None of them is a secret: a browser app has none.
Copy .env.example to .env.local, and put in the values from the Frontend section's Copy all. Vite builds only names that start with VITE_ into the page. Add roles to the scopes to read roles.
# Copy to .env.local. The values come from Connect an app's Frontend section (its Copy all), with VITE_ in front so
# Vite builds them into the page. None is a secret: a browser app has none. Add roles to the scopes to read roles.
VITE_IDENTITY_ISSUER=https://identity.example.com
VITE_IDENTITY_CLIENT_ID=your-client-id
VITE_IDENTITY_REDIRECT_URI=http://localhost:5173/callback
VITE_IDENTITY_SCOPES=openid profile email rolesCopy .env.example to .env.local, and put in the values from the Frontend section's Copy all. Vite builds only names that start with VITE_ into the page. Add roles to the scopes to read roles.
# Copy to .env.local. The values come from Connect an app's Frontend section (its Copy all), with VITE_ in front so
# Vite builds them into the page. None is a secret: a browser app has none. Add roles to the scopes to read roles.
VITE_IDENTITY_ISSUER=https://identity.example.com
VITE_IDENTITY_CLIENT_ID=your-client-id
VITE_IDENTITY_REDIRECT_URI=http://localhost:5173/callback
VITE_IDENTITY_SCOPES=openid profile email rolesPut the values from the Frontend section's Copy all in src/environments/environment.ts, with roles added to the scopes. For more than one environment, make one file each and pick it with fileReplacements in angular.json.
// The values from Connect an app's Frontend section (its Copy all). None is a secret: a browser app has none.
export const environment = {
identity: {
issuer: 'https://identity.example.com', // IDENTITY_ISSUER
clientId: 'your-client-id', // IDENTITY_CLIENT_ID
redirectUri: 'http://localhost:4200/callback', // IDENTITY_REDIRECT_URI
scopes: 'openid profile email roles', // IDENTITY_SCOPES, with roles added to read roles
},
};Install
A new app (skip the first three lines for an app you already have):
npm create vite@latest my-app -- --template react-ts --no-interactive
cd my-app
npm install
npm install oidc-client-ts react-router-domA new app (skip the first three lines for an app you already have):
npm create vite@latest my-app -- --template vue-ts --no-interactive
cd my-app
npm install
npm install oidc-client-ts vue-routerA new app (skip the first two lines for an app you already have):
npx @angular/cli@latest new my-app --routing --style=css --ssr=false --defaults
cd my-app
npm install oidc-client-tsAdd the code
Where these files go
src/auth/oidc.ts: the connection to OI, with sign-in and sign-out. Everything that signs people in imports from here.src/auth/useAuth.tsandsrc/auth/AuthProvider.tsx: the signed-in person, for every component.src/pages/Callback.tsx: the/callbackroute.src/App.tsxandsrc/main.tsx: the routes, and the provider around the app. These replace the starter's files.
import { UserManager } from 'oidc-client-ts';
// Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
// and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
export const userManager = new UserManager({
authority: import.meta.env.VITE_IDENTITY_ISSUER,
client_id: import.meta.env.VITE_IDENTITY_CLIENT_ID,
redirect_uri: import.meta.env.VITE_IDENTITY_REDIRECT_URI,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: import.meta.env.VITE_IDENTITY_SCOPES,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** Off to OI's sign-in page, which also has Register and Forgot password. */
export function signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
export function signOut(): Promise<void> {
return userManager.signoutRedirect();
}Where these files go
src/auth/oidc.ts: the connection to OI, with sign-in and sign-out. Everything that signs people in imports from here.src/auth/useAuth.ts: the signed-in person, shared by every component.src/views/CallbackView.vueandsrc/views/HomeView.vue: the/callbackroute and the front page.src/router/index.ts,src/App.vueandsrc/main.ts: the routes, and the app with its router. These replace the starter's files.
import { UserManager } from 'oidc-client-ts';
// Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
// and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
export const userManager = new UserManager({
authority: import.meta.env.VITE_IDENTITY_ISSUER,
client_id: import.meta.env.VITE_IDENTITY_CLIENT_ID,
redirect_uri: import.meta.env.VITE_IDENTITY_REDIRECT_URI,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: import.meta.env.VITE_IDENTITY_SCOPES,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** Off to OI's sign-in page, which also has Register and Forgot password. */
export function signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
export function signOut(): Promise<void> {
return userManager.signoutRedirect();
}Where these files go
src/app/auth/auth.service.ts: the connection to OI, with sign-in, sign-out and the signed-in person, as one service for the whole app.src/app/callback/callback.tsandsrc/app/home/home.ts: the/callbackroute and the front page.src/app/app.routes.tsandsrc/app/app.html: the routes, and a page that only shows them. These replace the starter's files.
import { Injectable, signal } from '@angular/core';
import { User, UserManager } from 'oidc-client-ts';
import { environment } from '../../environments/environment';
/**
* Otoko Identity, through oidc-client-ts. It reads OI's discovery document by itself, signs in with PKCE (no secret),
* and keeps the tokens in this tab's sessionStorage. Never move them to localStorage.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly userManager = new UserManager({
authority: environment.identity.issuer,
client_id: environment.identity.clientId,
redirect_uri: environment.identity.redirectUri,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: environment.identity.scopes,
loadUserInfo: true, // name, email and roles come from OI's userinfo endpoint
automaticSilentRenew: false, // when the access token expires, the person signs in again
});
/** The signed-in person, null when signed out. */
readonly user = signal<User | null>(null);
/** Whether who is signed in is known yet. */
readonly ready = signal(false);
constructor() {
this.userManager.events.addUserLoaded((loaded) => this.user.set(loaded));
this.userManager.events.addUserUnloaded(() => this.user.set(null));
this.userManager.events.addAccessTokenExpired(() => this.user.set(null));
this.userManager.getUser().then((current) => {
this.user.set(current && !current.expired ? current : null);
this.ready.set(true);
});
}
/** Off to OI's sign-in page, which also has Register and Forgot password. */
signIn(): Promise<void> {
// A fresh nonce ties the ID token to this sign-in. oidc-client-ts checks it when the browser comes back.
return this.userManager.signinRedirect({ nonce: crypto.randomUUID() });
}
/** Signs out of the app and of OI, which then sends the browser back to the front page. */
signOut(): Promise<void> {
return this.userManager.signoutRedirect();
}
/** On the callback page: checks the state, and swaps the code for tokens with the PKCE verifier. */
async completeSignIn(): Promise<void> {
try {
await this.userManager.signinRedirectCallback();
} catch (error) {
// A reload or Back on a used /callback ends up here: someone already signed in is fine.
if (!(await this.userManager.getUser())) {
throw error;
}
}
}
}Using something else?
The same oidc-client-ts code works in any front end. Put it here:
| Framework | Connection to OI | Signed-in person | Callback route |
|---|---|---|---|
| Svelte (SvelteKit, as a static app) | src/ | a store in src/ | src/ |
| Solid | src/ | a context in src/ | src/ |
| Next.js, exported as a static site | lib/ | a context in app/ | app/, a client component |
| Plain JavaScript | auth.js | a variable in auth.js | callback.html, which calls signinRedirectCallback() |
Run and check
npm run devOpen http://localhost:5173.
npm run devOpen http://localhost:5173.
npm startOpen http://localhost:4200.
- Choose Sign in. OI's sign-in page opens.
- Choose Register, fill in the form, and type the code OI emails you. You're back on the front page, signed in, with your name and email.
- In the console, give yourself the
memberrole, then sign out and in again. The page says Roles: member. - Choose Sign out, then Sign in again. OI asks for your email: its own session ended too.
- In the browser's developer tools, under Application, the tokens are in Session storage, and nothing is in Local storage.
When the access token expires, the page shows Sign in again. While OI's own session is still open, signing in comes straight back without a password.
Before going live
- Use https for your app and for Otoko Identity. Only
localhostmay use http. - Add your live addresses to the client, on its page in the console: the sign-in return address under Valid redirect URIs, and the front page under Valid post-logout redirect URIs. They're compared exactly, character for character.
- Build once per environment. The settings are built into the page, so each environment (staging, live) gets its own build with its own values.
- If you set a Content Security Policy, allow
connect-srcto Otoko Identity's address, as the page calls its token and userinfo endpoints. - Keep secrets out of the browser. A browser app has no client secret, and never holds an API key: anything in the page can be read.
- Keep the tokens where oidc-client-ts puts them, in sessionStorage. Never move them to localStorage.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
OI answers invalid_redirect_uri instead of showing its sign-in page | The sign-in return address isn't on the client's list, exactly | Make VITE_IDENTITY_REDIRECT_URI (or redirectUri) and the client's Valid redirect URIs the same, character for character. |
| The browser's console shows a CORS error from OI | The page's address isn't the origin of one of the client's redirect addresses | Add the app's real address to the client's Valid redirect URIs. |
/callback says No matching state found in storage | The sign-in started in another tab or browser, or the storage was cleared | Choose Try again. |
| OI's sign-in page has no Register link | Allow sign-up is off on the client, or Sign-up allowed is off on the app | Turn them on, as in step 1. |
| Roles: none | roles isn't in the scopes, the person has no role yet, or they haven't signed in since getting it | Add roles to the scopes, give the role in the console, and sign in again. |
| Signed out after a while | The access token expired | Sign in again. This quickstart doesn't renew tokens in the background. |
Tested with React 19.3.1, Vite 8.3.6, react-router-dom 7.18.6 · Vue 3.5.44, vue-router 5.5.1 · Angular 22.3.0 · oidc-client-ts 3.5.0 · TypeScript 6.0 and 7.0.