Skip to content

Commit

Permalink
Automatically refresh the auth token in the example app (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorreece authored Aug 16, 2024
1 parent 8aca872 commit bd0008f
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion example-embedded-app/pages/api/prismatic-auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default function handler(_req, res) {
customer: config.customer,
nbf: currentTime,
iat: currentTime,
exp: currentTime + 60 * 60 * 4, // 4 hours from now
exp: currentTime + config.tokenValidSeconds,
role: config.role,
},
config.signingKey, // Store this somewhere safe
Expand Down
7 changes: 7 additions & 0 deletions example-embedded-app/prismatic/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,11 @@ export interface PrismaticConfig {
* for documentation
*/
prismaticRefreshToken?: string;

/**
* Duration the auth token is valid in seconds.
* usePrismaticAuth.ts will automatically refresh the auth token
* 30 seconds before it expires.
*/
tokenValidSeconds: number;
}
2 changes: 2 additions & 0 deletions example-embedded-app/src/usePrismaticAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import axios from "axios";
import Router from "next/router";
import prismatic from "@prismatic-io/embedded";
import React, { useEffect, useMemo } from "react";
import config from "../prismatic/config";

interface UserInfoProps {
authenticatedUser: {
Expand Down Expand Up @@ -46,6 +47,7 @@ const usePrismaticAuth = (): AuthConfig => {
const { data, error } = useSWR<{ token: string }>(
"/api/prismatic-auth",
fetcher,
{ refreshInterval: (config.tokenValidSeconds - 30) * 1000 }, // Refresh token 30 seconds before expiration
);

const token = useMemo(() => data?.token, [data?.token]);
Expand Down

0 comments on commit bd0008f

Please sign in to comment.