Skip to content

Quickstart: React single-page application

This page gets a React application built with Vite signing people in through your issuer with oidc-client-ts: a public client with PKCE and no secret, the person’s ID on the page, automatic renewal with the refresh token, and sign-out. It applies Sign users in with OpenID Connect and takes about ten minutes.

  • Node.js 20 or later.
  • A public client on your issuer with none as the token endpoint authentication, the redirect URIs http://localhost:5173/callback and http://localhost:5173/silent-renew.html, and the post-logout redirect URI http://localhost:5173/. See Register a client.
  • The application’s origin allowed for CORS: http://localhost:5173 on the issuer or on the client, and the production origin when you deploy. See Call the issuer from a browser application.
Terminal window
npm create vite@latest authwise-spa -- --template react-ts
cd authwise-spa
npm install && npm install oidc-client-ts

This page was verified with Vite 8.3, React 19.3, and oidc-client-ts 3.5. Delete the scaffold’s App.css, index.css, and src/assets, and their imports, so the files below stand alone.

Create .env with the issuer and the client:

VITE_AUTHWISE_ISSUER=https://login.example.com
VITE_AUTHWISE_CLIENT_ID=CLIENT_ID

Replace https://login.example.com with your issuer’s URL and CLIENT_ID with the client’s ID. Vite inlines these values at build time.

Pin the port in vite.config.ts, because the redirect URIs are registered for port 5173 exactly:

import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
// The redirect URIs are registered for http://localhost:5173 exactly;
// fail instead of falling back to another port.
server: { port: 5173, strictPort: true },
})

Create src/auth.ts:

import { UserManager } from 'oidc-client-ts'
const origin = window.location.origin
export const userManager = new UserManager({
authority: import.meta.env.VITE_AUTHWISE_ISSUER,
client_id: import.meta.env.VITE_AUTHWISE_CLIENT_ID,
redirect_uri: `${origin}/callback`,
post_logout_redirect_uri: `${origin}/`,
silent_redirect_uri: `${origin}/silent-renew.html`,
response_type: 'code',
scope: 'openid profile email offline_access',
automaticSilentRenew: true,
})

offline_access asks for a refresh token, and automaticSilentRenew uses it to renew the access token a minute before it expires, without any navigation. The silent-redirect page is the library’s fallback when no refresh token is present; see Good to know for why it stays a fallback.

Replace src/App.tsx:

import { useEffect, useState } from 'react'
import type { User } from 'oidc-client-ts'
import { userManager } from './auth'
// Finish the redirect exactly once per page load (React StrictMode runs
// effects twice in development), then put the URL back to "/".
const initialUser: Promise<User | null> =
window.location.pathname === '/callback'
? userManager.signinCallback().then((user) => {
window.history.replaceState(null, '', '/')
return user ?? null
})
: userManager.getUser()
export default function App() {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string>()
useEffect(() => {
initialUser
.then(setUser, (e: unknown) => setError(String(e)))
.finally(() => setLoading(false))
// Fired after every sign-in and every renewal, automatic or manual.
const onUnloaded = () => setUser(null)
userManager.events.addUserLoaded(setUser)
userManager.events.addUserUnloaded(onUnloaded)
return () => {
userManager.events.removeUserLoaded(setUser)
userManager.events.removeUserUnloaded(onUnloaded)
}
}, [])
if (loading) return <p>Loading…</p>
if (!user) {
return (
<main>
<button onClick={() => userManager.signinRedirect()}>Sign in</button>
{error && <p role="alert">{error}</p>}
</main>
)
}
return (
<main>
<p>
Signed in as <code id="sub">{user.profile.sub}</code>
</p>
<p>
Access token expires at{' '}
<time id="expires">{new Date(user.expires_at! * 1000).toISOString()}</time>
</p>
<button onClick={() => userManager.signinSilent().then(setUser, (e: unknown) => setError(String(e)))}>
Renew now
</button>{' '}
<button onClick={() => userManager.signoutRedirect()}>Sign out</button>
{error && <p role="alert">{error}</p>}
</main>
)
}

Add public/silent-renew.html, the static page the fallback loads in a hidden iframe:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Silent renew</title>
</head>
<body>
<!--
Loaded in a hidden iframe by oidc-client-ts when it renews without a
refresh token (prompt=none). It must be a plain page, not a route of the
React app: all it does is hand the callback URL back to the opener.
Pin the same version as package.json.
-->
<script src="https://cdn.jsdelivr.net/npm/oidc-client-ts@3.5.0/dist/browser/oidc-client-ts.min.js"></script>
<script>
new oidc.UserManager({}).signinSilentCallback()
</script>
</body>
</html>
Terminal window
npm run dev

Open http://localhost:5173/, click Sign in, and sign in on the hosted page. The app shows Signed in as u-… and the access token’s expiry. Renew now moves the expiry forward with one request to the token endpoint and no page change. Sign out ends the issuer session and returns to http://localhost:5173/.

  • Renewal is the refresh token. The issuer’s session cookie is SameSite=Lax, so a hidden iframe on your application’s origin cannot carry it, and a prompt=none request from that iframe answers login_required. With offline_access the library renews with the refresh token and never opens the iframe. Keep the scope.
  • Tokens live in sessionStorage, per tab, under oidc.user:AUTHORITY:CLIENT_ID. To share a sign-in across tabs, pass userStore: new WebStorageStateStore({ store: localStorage }).
  • Refresh tokens rotate on every renewal. The library stores the newest one for you; a reused one is refused.
  • signinCallback() consumes the state once. The sample runs it at module scope so React’s development double-render does not call it twice.
  • The silent-renew page must be a plain static file at a registered redirect URI, not a route of the React app. In Vite, files under public/ cannot import from src/, which is why it loads the pinned browser bundle.
  • Listen to events.addSilentRenewError in a real application and start an interactive sign-in when it fires.
  • Send user.access_token as a bearer token to the API the client’s audience names, and validate it there against the issuer’s JWKS.
  • Read Keep the session alive for the refresh token lifetimes and how to tune them.