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.
- GET /authorize
oidc-spaoidc-spa/server- Waiting…
Your frontend is the OpenID Connect client.
It obtains tokens directly from your identity provider and uses them to call your APIs.
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.
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/
Paste it into your coding agent of choice. It will start from the closest example and set everything up.
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.
- Authorization Code Flow with PKCEThe OpenID Connect flow designed for public clients. An intercepted code is useless without the verifier only your app holds.(opens in a new tab)
- In-memory tokens by defaultTokens never touch localStorage or sessionStorage, and sessions are still restored transparently on reload.(opens in a new tab)
- DPoPTokens are bound to a private key held by your app. In auto mode, it is used whenever your provider supports it.(opens in a new tab)
- Token substitutionYour code only ever sees tokens with a fake signature. The real one is restored as the request leaves, for trusted hosts only.(opens in a new tab)
- Browser runtime freezeCore APIs like fetch are frozen before your app loads, so no script can patch them to steal tokens.(opens in a new tab)
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.
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.
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.
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.
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 };};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.
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();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.
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"]});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.
-import Keycloak from "keycloak-js";+import { Keycloak } from "oidc-spa/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.
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"});