oidc-spa

The OpenID Connect TypeScript toolkit for apps that live in the browser.

A single MIT library to connect your frontend to your identity provider, deliver a smooth sign-in experience, and authenticate requests to your APIs.

Your identity providerKeycloak
auth.example.com
  • GET /authorize
Your app in the browserOne tab, using oidc-spa
app.example.com
Todos
Sign in to see your todosSign in
Your APIusing oidc-spa/server
api.example.com
  • Waiting…
1/6The app redirects to the provider
How it works

Your frontend is the OpenID Connect client.

It obtains tokens directly from your identity provider and uses them to call your APIs.

Typical server-side OIDC
Backend is the client
  1. 1The browser is redirected to the identity provider
  2. 2Your backend exchanges the code and keeps the tokens
  3. 3The browser gets an application session cookie
  4. 4Every request is checked against your session store
With oidc-spa
Frontend is the client
  1. 1The browser is redirected to the identity provider
  2. 2Your frontend exchanges the code for tokens (PKCE)
  3. 3Requests to your API carry an access token
  4. 4Your API validates the token, no session store needed
Trusted in production by
Getting started

One library for all your auth needs.

A single MIT library covering authentication and authorization. Build your setup prompt below, or head over to the docs.

1Your identity provider

Using another provider? Any standard OpenID Connect provider works, see the setup guide.

2Your frontend
Router
3Your backend
Frameworks
Runtimes

Backend not in JavaScript? Validate the access token with any JWT library, here is how.

Your prompt

Set up a fresh todo app with this stack: - Identity provider: Keycloak (use offline token validation) - Auth library: oidc-spa - Frontend: Vite + React, with TanStack Router - Backend: tRPC Start from the most relevant example in: https://github.com/keycloakify/oidc-spa/tree/v11_overhaul/examples Follow these guides: https://docs.oidc-spa.dev/docs/v11/providers-configuration/keycloak https://docs.oidc-spa.dev/docs/v11/integration-guides/tanstack-router-start https://docs.oidc-spa.dev/docs/v11/integration-guides/backend-token-validation/trpc

Paste it into your coding agent of choice. It will start from the closest example and set everything up.

Security

Security built for browser-first apps.

Keeping tokens safe in the browser takes more than implementing a login flow. oidc-spa brings together protections designed for this architecture.

Sessions

A great session experience out of the box.

Give your users smooth authentication without building all the session plumbing yourself.

  • Automatic token renewal and session restoration.
  • Login and logout propagation across tabs.
  • Inactivity logout warnings with a countdown your UI can display.

When a session is about to expire, give users a chance to keep working. Watch it in action, or read about auto logout.

Setup

Remarkably easy to set up.

  • One single redirect URIThe home of your app. That's it.
  • No third-party cookie worriesoidc-spa automatically uses the best session restoration strategy your deployment configuration allows.
  • Built-in diagnosticsWhen the provider configuration needs attention, get actionable guidance about discovery, redirect URIs and iframe restrictions.
Console
The silent sign-in process timed out.
Based on the diagnostic performed by oidc-spa the more likely causes are:
- Either the client ID "myclient" does not exist, or
- You forgot to add the OIDC callback URL to the list of Valid Redirect URIs.
Client ID: "myclient"
Callback URL to add to the list of Valid Redirect URIs: "https://my-app.example.com/"

It seems you are using Keycloak. Follow these steps to resolve the issue:

1. Go to the Keycloak admin console: https://auth.example.com/admin/master/console
2. Log in as an admin user.
3. In the top left corner select the realm "myrealm".
4. In the left menu, click on "Clients".
5. Locate the client "myclient" in the list and click on it.
6. Find "Valid Redirect URIs" and add "https://my-app.example.com/" to the list.
7. Save the changes.
Typed users

Your user object, your way.

You decide what a user looks like in your application. Give oidc-spa one function that creates that representation, and use the result throughout your app with full TypeScript support.

Build it from ID token claims, access token claims, the userinfo endpoint, your own API, or a combination of those sources.

Learn more about the user object
src/oidc.user.ts
import type { CreateUser } from "oidc-spa/core";import { z } from "zod";export type User = { displayName: string; avatarUrl?: string };const DecodedIdToken = z.object({    name: z.string(),    picture: z.string().optional()});export const createUser: CreateUser<User> = ({ decodedIdToken }) => {    const { name, picture } = DecodedIdToken.parse(decodedIdToken);    return { displayName: name, avatarUrl: picture };};
Testing

Built with testability in mind.

Develop and test your app without connecting to a live authentication server. Mock mode gives you realistic users and control over the initial login state, on both the frontend and backend.

Use it for automated tests, local development, demos, or a deliberately configured mode that does not require real authentication.

Learn more about mock modes
src/oidc.ts
import { oidcSpa } from "oidc-spa/react-tanstack-start";import { z } from "zod";type User_client = { displayName: string };type User_server = { isAdmin: boolean };const AccessTokenClaims = z.object({ roles: z.array(z.string()) });export const { useOidc, getOidc } = oidcSpa    .withClientUser<User_client>(({ isMock, idTokenClaims }) => {        if (isMock) return { displayName: "John Doe" };        return { displayName: idTokenClaims.name };    })    .withServerUser<User_server>(({ isMock, accessTokenClaims }) => {        if (isMock) return { isAdmin: true };        const { roles } = AccessTokenClaims.parse(accessTokenClaims);        return { isAdmin: roles.includes("admin") };    })    .withRuntimeConfigs(({ process }) => {        if (process.env["OIDC_MOCK"] === "true") {            return { mode: "mock", client: { isUserInitiallyLoggedIn: true } };        }        return {            mode: "real",            issuerUri: process.env["ISSUER_URI"],            client: { clientId: process.env["CLIENT_ID"] },            server: {                accessTokenValidationMethod: "offline JWT validation",                expectedAccessTokenAudience: process.env["EXPECTED_ACCESS_TOKEN_AUDIENCE"]            }        };    })    .createUtils();
Multiple APIs

Talk to multiple APIs.

Your app may need more than one access token. Request the scopes or authorization parameters required by each API, and let oidc-spa manage the corresponding tokens and their renewal.

Your appOne token per API
src/api.ts
import { getOidc } from "./oidc";const oidc = await getOidc({ assert: "user logged in" });const myApiToken = await oidc.getAccessToken({    scopes: ["resource:myapp-api"]});const vaultToken = await oidc.getAccessToken({    scopes: ["resource:vault"]});const s3Token = await oidc.getAccessToken({    scopes: ["resource:aws-s3"]});
Learn more about multiple access tokens
Keycloak

Built with Keycloak users in mind.

Already using keycloak-js? Bring oidc-spa's session handling and security features into your application without any migration work. We provide a polyfill for it.

src/keycloak.ts
-import Keycloak from "keycloak-js";+import { Keycloak } from "oidc-spa/keycloak-js";
Migrating from keycloak-js

And when you are ready to actually migrate, oidc-spa exposes Keycloak-specific utilities, available independently. Fetch user profiles, open the account console, or direct users to registration with a small set of dedicated helpers.

src/account.ts
import { createKeycloakUtils } from "oidc-spa/keycloak";import { getOidc } from "./oidc";const oidc = await getOidc({ assert: "user logged in" });const keycloakUtils = createKeycloakUtils({ issuerUri: oidc.issuerUri });const userProfile = await keycloakUtils.fetchUserProfile({    accessToken: await oidc.getAccessToken()});const accountConsoleUrl = keycloakUtils.getAccountUrl({    clientId: oidc.clientId,    validRedirectUri: oidc.validRedirectUri,    locale: "fr"});
Learn more about the Keycloak utilities
Sponsors

Backed by our sponsors

Phase Two
Keycloak as a Service
Keycloak community contributors building popular extensions, managed hosting, and enterprise support. Get the flexibility of Keycloak with the expertise to run it for businesses of all sizes.