Skip to content

Instantly share code, notes, and snippets.

@micaiah-effiong
Created August 22, 2024 16:27
Show Gist options
  • Select an option

  • Save micaiah-effiong/6a4a8297d0017caf6fa9261c094329f9 to your computer and use it in GitHub Desktop.

Select an option

Save micaiah-effiong/6a4a8297d0017caf6fa9261c094329f9 to your computer and use it in GitHub Desktop.
import { jwtDecode } from "jwt-decode";
import * as api from "./generated";
import { ApiRequestOptions } from "./generated/core/ApiRequestOptions";
import { toast } from "react-toastify";
import { storageKey } from "@/utils/keys";
api.OpenAPI.BASE = import.meta.env.VITE_APP_BASE_API;
export const apiConfig = api;
apiConfig.OpenAPI.TOKEN = async (_: ApiRequestOptions) => {
const token = getTokenFromStore(storageKey.token);
console.log("getting token", token);
return token;
};
export function getTokenFromStore(key: string) {
const rawToken = localStorage.getItem(key) ?? "null";
const parsedToken = JSON.parse(rawToken) ?? null;
if (parsedToken === null) {
return parsedToken;
}
const decoded = jwtDecode(rawToken);
const expireAt = (decoded.exp || 0) * 1000;
if (expireAt < Date.now()) {
localStorage.setItem(key, JSON.stringify(null));
localStorage.setItem(storageKey.user, JSON.stringify(null));
toast.error("Token expired", {});
window.location.replace("/login");
return null;
}
return parsedToken;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment