Framework Agnostic Adapter
Let's get your App authenticated!
Installation
npm install oidc-spayarn add oidc-spapnpm add oidc-spabun add oidc-spaTo protect tokens against supply-chain attacks and XSS, oidc-spa must run some initialization code before any other JavaScript in your app.
This design provides much stronger security guarantees than any other adapter, and it also delivers unmatched login performance. More details here.
In Vite apps, this is done through a Vite Plugin (If you'd rather avoid using the Vite plugin checkout the Other SPAs tab).
import { defineConfig } from "vite";
import { oidcSpa } from "oidc-spa/vite-plugin";
export default defineConfig({
plugins: [
// ...
oidcSpa()
]
});First rename your entry point file from main.tsx (or main.ts or whatever it is) to main.lazy.tsx
mv src/main.ts src/main.lazy.tsThen create a new index.tsx file:
import { oidcEarlyInit } from "oidc-spa/entrypoint";
const { shouldLoadApp } = oidcEarlyInit({
BASE_URL: "/" // The path where your app is hosted, can also be provided later to createOidc()
});
if (shouldLoadApp) {
// Note: Deferring the main app import adds a few milliseconds to cold start,
// but dramatically speeds up auth. Overall, it's a net win.
import("./index.lazy");
}If you don't have a precise entrypoint that you can simply override, just call oidcEarlyInit as soon as possible and try canceling as much work as possible when shouldLoadApp is false.
Basic Usage
Mock Adapter
For certain use cases, you may want a mock adapter to simulate user authentication without involving an actual authentication server.
This approach is useful when building an app where user authentication is a feature but not a requirement. It also proves beneficial for running tests or in Storybook environments.
Creating an API server
Now that authentication is handled, there’s one last piece of the puzzle: your resource server, the backend your app will communicate with.
This can be any type of service: a REST API, tRPC server, or WebSocket endpoint, as long as it can validate access tokens issued by your IdP.
If you’re building it in JavaScript or TypeScript (for example, using Express), oidc-spa provides ready-to-use utilities to decode and validate access tokens on the server side.
You’ll find the full documentation here:
Creating an API ServerLast updated
Was this helpful?