Web API
Client Side
import { createOidc } from "oidc-spa";
export const prOidc = createOidc({/* ... */});import axios from "axios";
import { prOidc } from "./oidc";
type Api = {
getTodos: () => Promise<{ id: number; title: string; }[]>;
addTodo: (todo: { title: string; }) => Promise<void>;
};
const axiosInstance = axios.create({ baseURL: import.meta.env.API_URL });
axiosInstance.interceptors.request.use(async config => {
const oidc= await prOidc;
if( !oidc.isUserLoggedIn ){
throw new Error("We made a logic error: If the user isn't logged in we shouldn't be making request to an API endpoint that requires authentication");
}
// 99.9% of the times you'll get the token imediately.
// The 0.1% is after the computer wakes up from sleep.
const { accessToken } = await oidc.getTokens_next();
config.headers.Authorization = `Bearer ${accessToken}`;
return config;
});
export const api: Api = {
getTodo: ()=> axiosInstance.get("/todo").then(response => response.data),
addTodo: todo => axiosInstance.post("/todo", todo).then(response => response.data)
};Server Side
Testable example
Full-Stack with Node REST APILast updated
Was this helpful?