👨‍🔧Basic Usage

Let's get your App authenticated!

In this guide, we assume that you have an OIDC-enabled authentication server in place, such as Keycloak.

If you have not yet set up such a server, please refer to our guide for instructions on how to provision and configure a Keycloak server.

import { createOidc } from "oidc-spa";

const oidc = await createOidc({
    issuerUri: "https://auth.your-domain.net/realms/myrealm",
    clientId: "myclient",
    /**
     * Vite:  `publicUrl: import.meta.env.BASE_URL`
     * CRA:   `publicUrl: process.env.PUBLIC_URL`
     * Other: `publicUrl: "/"` (Usually)
     */
    publicUrl: import.meta.env.BASE_URL
});

if (!oidc.isUserLoggedIn) {
    // The user is not logged in.

    // We can call login() to redirect the user to the login/register page.
    // This return a promise that never resolve. 
    oidc.login({
         /** 
          * If you are calling login() in the callback of a click event
          * set this to false.  
          */
         doesCurrentHrefRequiresAuth: false
         /** 
          * Optionally, you can add some extra parameter 
          * to be added on the login url.  
          * (This can also be a parameter of createOidc)
          */
         //extraQueryParams: { kc_idp_hint: "google", kc_locale: "fr" }
         /**
          * You can allso set where to redirect the user after 
          * successful login
          */
          // redirectUrl: "/dashboard"
    });

} else {
    // The user is logged in.

    const {
        // The accessToken is what you'll use as a Bearer token to 
        // authenticate to your APIs
        accessToken,
        decodedIdToken
    } = oidc.getTokens();

    fetch("https://api.your-domain.net/orders", {
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    })
     .then(response => response.json())
     .then(orders => console.log(orders));

    // To call when the user click on logout.
    // You can also redirect to a custom url with 
    // { redirectTo: "specific url", url: `${location.origin}/bye` }
    oidc.logout({ redirectTo: "home" });

    // If you are wondering why ther's a decodedIdToken and no
    // decodedAccessToken read this: https://docs.oidc-spa.dev/resources/jwt-of-the-access-token
    console.log(`Hello ${decodedIdToken.preferred_username}`);

    // Note that in this example the decodedIdToken is not typed.  
    // What is inside the idToken is defined by the OIDC server you are using.  
    // If you want to specify the type of the decodedIdToken you can do:
    //
    // type DecodedIdToken = {
    //    sub: string;
    //    preferred_username: string;
    //    // ...
    // };
    //
    // export const { useOidc } = createUseOidc<DecodedIdToken>(...)
    //
    // If you want the shape of the decodedIdToken to be validated at runtime
    // you can provide a validator function using zod for example:
    //
    // export const { useOidc } = createUseOidc<DecodedIdToken>({
    //    ...
    //    decodedIdTokenSchema: z.object({
    //        sub: z.string(),
    //        preferred_username: z.string()
    //    })
    // })

}

Last updated