RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to a React app

Add Keycloak login to a React single-page app built with Vite, using oidc-client-ts and react-oidc-context with the code flow and PKCE.

A React single-page app signs users in with the authorization code flow and PKCE. It runs entirely in the browser and cannot keep a secret, so the client is public.

Written against oidc-client-ts 3.5, react-oidc-context 3.3, React 19.3, Vite 8.3, jose 6.2 and Keycloak 26.8, checked on 25 November 2026.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

We use react-oidc-context on top of oidc-client-ts. Both come from the same maintainers (the authts project), and their latest releases came out together. The wrapper handles the redirect back from Keycloak and gives components the login state through a useAuth hook; everything else is oidc-client-ts's own UserManager, with the same settings.

Create the client in Keycloak

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDreact-app
Client authenticationOff
Authentication flowStandard flow. Turn Direct access grants off.
PKCE MethodS256
Root URLhttp://localhost:5173
Valid redirect URIshttp://localhost:5173/
Valid post logout redirect URIshttp://localhost:5173/
Web originshttp://localhost:5173

Choose Save. A public client has no Credentials tab and no secret.

Web origins matters here: the browser calls Keycloak's token endpoint from JavaScript, and Keycloak answers that cross-origin request only for the origins listed. The Web origins helper explains the values.

For production, add your app's real URLs next to the local ones, for example https://app.example.com/ and the origin https://app.example.com. Keycloak compares redirect URIs exactly.

Environment variables

.env.local
VITE_OIDC_AUTHORITY=https://auth.example.com/realms/acme
VITE_OIDC_CLIENT_ID=react-app
VITE_API_URL=http://localhost:3000

Vite puts every VITE_ variable into the JavaScript bundle, so put only public values here. A public client has nothing secret to hide. Declare their types in a new file:

src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_OIDC_AUTHORITY: string
  readonly VITE_OIDC_CLIENT_ID: string
  readonly VITE_API_URL: string
}

Install

npm create vite@latest react-app -- --template react-ts
cd react-app
npm install oidc-client-ts react-oidc-context

Add login

oidc-client-ts uses the authorization code flow and PKCE by default, so neither needs a setting.

src/main.tsx
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { AuthProvider, type AuthProviderProps } from "react-oidc-context"
import App from "./App"

const oidcConfig: AuthProviderProps = {
  authority: import.meta.env.VITE_OIDC_AUTHORITY,
  client_id: import.meta.env.VITE_OIDC_CLIENT_ID,
  redirect_uri: `${window.location.origin}/`,
  post_logout_redirect_uri: `${window.location.origin}/`,
  scope: "openid profile email",
  // Remove ?code=...&state=... from the address bar after login.
  onSigninCallback: () => {
    window.history.replaceState({}, document.title, window.location.pathname)
  },
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AuthProvider {...oidcConfig}>
      <App />
    </AuthProvider>
  </StrictMode>,
)
src/App.tsx
import { useAuth } from "react-oidc-context"

export default function App() {
  const auth = useAuth()

  if (auth.isLoading) return <p>Loading...</p>
  if (auth.error) return <p>Sign-in failed: {auth.error.message}</p>

  if (!auth.isAuthenticated) {
    return <button onClick={() => void auth.signinRedirect()}>Log in</button>
  }

  async function callApi() {
    const response = await fetch(`${import.meta.env.VITE_API_URL}/api/me`, {
      headers: { Authorization: `Bearer ${auth.user?.access_token}` },
    })
    console.log(await response.json())
  }

  return (
    <main>
      <p>Signed in as {auth.user?.profile.preferred_username}</p>
      <button onClick={() => void callApi()}>Call API</button>
      <button onClick={() => void auth.signoutRedirect()}>Log out</button>
    </main>
  )
}

The react-oidc-context README says onSigninCallback is required: without it the code stays in the address bar, and renewing the token fails after a page reload. Run npm run dev, open http://localhost:5173 and sign in with a user of your realm.

oidc-client-ts keeps the tokens in the browser's sessionStorage by default, which any script on the page can read. That is the trade-off of a pure single-page app; for apps that handle sensitive data, put a backend-for-frontend in front of it that keeps the tokens on the server and gives the browser only a session cookie, as in the Next.js or Express guides.

Protect an API

The app sends the access token to your API as Authorization: Bearer <access token>. The API must check the token's signature, issuer and audience before it trusts it.

Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to this client:

  1. Open Clients, choose react-app, and open its Client scopes tab.
  2. Choose react-app-dedicated.
  3. Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
  4. Enter a Name, set Included Custom Audience to orders-api, keep Add to access token on, and choose Save.

Sign in again to get a token with the new audience. On the API side, a Node.js check with jose looks like this (set OIDC_ISSUER to https://auth.example.com/realms/acme and API_AUDIENCE to orders-api):

api/verify-token.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose"

const issuer = process.env.OIDC_ISSUER!
const audience = process.env.API_AUDIENCE

// The realm's public signing keys. jose caches them and fetches
// them again when a token arrives with a key ID it has not seen.
const jwks = createRemoteJWKSet(new URL(`${issuer}/protocol/openid-connect/certs`))

export async function verifyBearerToken(request: Request): Promise<JWTPayload | null> {
  // jose skips the audience check when audience is undefined, so fail loudly.
  if (!audience) throw new Error("API_AUDIENCE is not set")

  const header = request.headers.get("authorization")
  if (!header?.startsWith("Bearer ")) return null

  try {
    const { payload } = await jwtVerify(header.slice("Bearer ".length), jwks, {
      issuer,
      audience,
    })
    return payload
  } catch {
    return null
  }
}

It takes a standard Request, so it fits any runtime with the Fetch API. For an Express middleware, see Protect an API in the Express guide. Your API on another origin must also answer CORS requests from http://localhost:5173; the CORS checker shows what it sends back.

Log out

auth.signoutRedirect() removes the stored user, then sends the browser to the realm's end-session endpoint with the ID token as id_token_hint and post_logout_redirect_uri from the settings. Keycloak ends its session without asking and sends the user back to http://localhost:5173/, which must be listed in Valid post logout redirect URIs.

auth.removeUser(), used in the react-oidc-context README, only forgets the tokens in the browser. The Keycloak session stays, and the next login goes straight through without a password.

Common errors

ErrorCauseFix
Keycloak shows Invalid parameter: redirect_urihttp://localhost:5173/ is not in Valid redirect URIs, or differs in scheme, port or trailing slash.Add it exactly. Compare both with the redirect URI matcher.
Browser console: the token request was blocked by CORS policyThe app's origin is not in Web origins.Add http://localhost:5173, without a path or trailing slash.
No matching state found in storageThe login started on one origin and came back on another, for example 127.0.0.1 and localhost, or the callback URL was reloaded.Use one origin everywhere and start the login again.
Token request fails with unauthorized_clientClient authentication is on, so Keycloak expects a secret.Turn Client authentication off for this client.
Keycloak shows Invalid redirect uri after Log outpost_logout_redirect_uri is not in Valid post logout redirect URIs.Add http://localhost:5173/.
API returns 401, jose says unexpected "aud" claim valueThe access token has no orders-api audience.Add the Audience mapper above and sign in again.

Decode a token with the JWT decoder to see its iss, aud and expiry. For other OAuth error codes, see the OAuth error lookup.

FAQ

Why react-oidc-context and not oidc-client-ts alone?

Either works. The wrapper saves you the callback handling and a React context of your own; the Vue guide shows the same client with UserManager directly.

Does the token renew itself?

Yes. automaticSilentRenew is on by default in oidc-client-ts, and it uses the refresh token Keycloak issues when the access token is about to expire.

How do I protect a route in the app?

Check auth.isAuthenticated before rendering it, or wrap the component with withAuthenticationRequired from react-oidc-context. This only decides what the browser shows; the API must still check every token.

Can I store tokens in localStorage instead?

oidc-client-ts accepts userStore: new WebStorageStateStore({ store: window.localStorage }), which keeps users signed in across tabs and restarts. It is no safer than sessionStorage, and the tokens live longer on the device.

Sources

On this page