Installation

There are known issues with the v6 of oidc-spa. I'm actively working on it.

Before starting be aware that oidc-spa is not suited for Next.js or any other framwork that involves server side rendering.

If you are using Next the closer alternative is to use NextAuth.js (with the Keycloak adapter if you are using Keycloak). See this guide.

If you're having issues don't hesitate to reach out on Discord!

Let's install oidc-spa in your project:

npm install oidc-spa

Create the oidc-callback. file in your public/ directory:

public/oidc-callback.htm
<!doctype html>
<html>
<body>
    <!-- oidc-spa file. Do not remove, do not edit -->
    <script>
        if (localStorage.getItem("oidc-spa.callback-file-version") !== "2") { alert("Your oidc-callback.htm file is outdated. Please update it. https://docs.oidc-spa.dev/v/v6"); } const authResponse = {}; for (const [key, value] of new URL(location.href).searchParams) { authResponse[key] = value; } const reloadOnRestore = ()=> { const listener = ()=> { if (document.visibilityState === "visible") { document.removeEventListener("visibilitychange", listener); location.reload(); } }; document.addEventListener("visibilitychange", listener); }; const stateJson = localStorage.getItem(`oidc.${authResponse.state}`); if (!stateJson || stateJson === "null") { reloadOnRestore(); const KEY = "oidc-spa.has-navigated-back"; if (sessionStorage.getItem(KEY) === "true") { sessionStorage.removeItem(KEY); history.forward(); } else { sessionStorage.setItem(KEY, "true"); history.back(); } } const { data } = JSON.parse(stateJson); if (data.isSilentSso) { parent.postMessage(authResponse, location.origin); } else { reloadOnRestore(); const redirectUrl = new URL(data.redirectUrl); for (const [key, value] of Object.entries(authResponse)) { redirectUrl.searchParams.set(`oidc-spa.${key}`, value); } location.href = redirectUrl.href; }
    </script>
</body>
</html>

On your OIDC Server, in your client configuration, define Valid Redirect URIs: https://oidc-callback.htm, http://localhost:/oidc-callback.htm. More infos.

Doing without the oidc-callback.htm file

If for some reasons it's not fesable or practical for you to rely on the oidc-callback.htm it's fine, this file is only here for optimisation purposes but the lib works without it.

To let oidc-spa know that you won't be using the oidc-callback.htm file provide those parameter when initializing the adapter:

 export const { ... } = createOidc({
     // ...
-    BASE_URL: import.meta.env.BASE_URL,
+    BASE_URL: undefined
     // Provide the path of your homepage.
     // It's usually "/" but it can be for example "/dashboard"
     // If your app is accessible at https://your-domain.com/dashboard
+    homeUrl: "/"
 });

As Valid Redirec URIs use the home of your app without trailing shlash at the end. Example: https://my-app.com or https//my-app.com/dashboard and http://localhost:5173 or http://localhost:5173/dashboard

Last updated

Was this helpful?