-
Notifications
You must be signed in to change notification settings - Fork 6
feat: Add useAccessToken and useTokenClaims hooks #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nicknisi
wants to merge
2
commits into
main
Choose a base branch
from
nicknisi/use-custom-claims
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -37,6 +37,6 @@ | |
"react": ">=17" | ||
}, | ||
"dependencies": { | ||
"@workos-inc/authkit-js": "0.11.0" | ||
"@workos-inc/authkit-js": "0.12.0" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,222 @@ | ||
import { getClaims, type JWTPayload } from "@workos-inc/authkit-js"; | ||
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react"; | ||
import { useAuth } from "./hook"; | ||
|
||
interface TokenState { | ||
token: string | undefined; | ||
loading: boolean; | ||
error: Error | null; | ||
} | ||
|
||
type TokenAction = | ||
| { type: "FETCH_START" } | ||
| { type: "FETCH_SUCCESS"; token: string | undefined } | ||
| { type: "FETCH_ERROR"; error: Error } | ||
| { type: "RESET" }; | ||
|
||
function tokenReducer(state: TokenState, action: TokenAction): TokenState { | ||
switch (action.type) { | ||
case "FETCH_START": | ||
return { ...state, loading: true, error: null }; | ||
case "FETCH_SUCCESS": | ||
return { ...state, loading: false, token: action.token }; | ||
case "FETCH_ERROR": | ||
return { ...state, loading: false, error: action.error }; | ||
case "RESET": | ||
return { ...state, token: undefined, loading: false, error: null }; | ||
// istanbul ignore next | ||
default: | ||
return state; | ||
} | ||
} | ||
|
||
const TOKEN_EXPIRY_BUFFER_SECONDS = 60; | ||
const MIN_REFRESH_DELAY_SECONDS = 15; // minimum delay before refreshing token | ||
const RETRY_DELAY_SECONDS = 300; // 5 minutes | ||
|
||
interface TokenData { | ||
exp: number; | ||
timeUntilExpiry: number; | ||
isExpiring: boolean; | ||
} | ||
|
||
function parseToken(token: string): TokenData | null { | ||
try { | ||
const claims = getClaims(token); | ||
const now = Date.now() / 1000; | ||
const exp = claims.exp ?? 0; | ||
const timeUntilExpiry = exp - now; | ||
const isExpiring = timeUntilExpiry <= TOKEN_EXPIRY_BUFFER_SECONDS; | ||
|
||
return { exp, timeUntilExpiry, isExpiring }; | ||
} catch { | ||
return null; | ||
} | ||
} | ||
|
||
function getRefreshDelay(timeUntilExpiry: number): number { | ||
const refreshTime = Math.max( | ||
timeUntilExpiry - TOKEN_EXPIRY_BUFFER_SECONDS, | ||
MIN_REFRESH_DELAY_SECONDS, | ||
); | ||
return refreshTime * 1000; // convert to milliseconds | ||
} | ||
|
||
/** | ||
* A hook that manages access tokens with automatic refresh. | ||
* | ||
* @example | ||
* ```ts | ||
* const { accessToken, loading, error, refresh } = useAccessToken(); | ||
* ``` | ||
* | ||
* @returns An object containing the access token, loading state, error state, and a refresh function. | ||
*/ | ||
export function useAccessToken() { | ||
const auth = useAuth(); | ||
const user = auth.user; | ||
const userId = user?.id; | ||
const [state, dispatch] = useReducer(tokenReducer, { | ||
token: undefined, | ||
loading: false, | ||
error: null, | ||
}); | ||
|
||
const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout>>(); | ||
const fetchingRef = useRef(false); | ||
|
||
const clearRefreshTimeout = useCallback(() => { | ||
if (refreshTimeoutRef.current) { | ||
clearTimeout(refreshTimeoutRef.current); | ||
refreshTimeoutRef.current = undefined; | ||
} | ||
}, []); | ||
|
||
const updateToken = useCallback(async () => { | ||
if (fetchingRef.current || !auth) { | ||
return; | ||
} | ||
|
||
fetchingRef.current = true; | ||
dispatch({ type: "FETCH_START" }); | ||
try { | ||
let token = await auth.getAccessToken(); | ||
if (token) { | ||
const tokenData = parseToken(token); | ||
if (!tokenData || tokenData.isExpiring) { | ||
// Force refresh by getting a new token | ||
// The authkit-js client handles refresh internally | ||
token = await auth.getAccessToken(); | ||
} | ||
} | ||
|
||
dispatch({ type: "FETCH_SUCCESS", token }); | ||
|
||
if (token) { | ||
const tokenData = parseToken(token); | ||
if (tokenData) { | ||
const delay = getRefreshDelay(tokenData.timeUntilExpiry); | ||
clearRefreshTimeout(); | ||
refreshTimeoutRef.current = setTimeout(updateToken, delay); | ||
} | ||
} | ||
|
||
return token; | ||
} catch (error) { | ||
nicknisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dispatch({ | ||
type: "FETCH_ERROR", | ||
error: error instanceof Error ? error : new Error(String(error)), | ||
}); | ||
refreshTimeoutRef.current = setTimeout( | ||
updateToken, | ||
RETRY_DELAY_SECONDS * 1000, | ||
); | ||
} finally { | ||
fetchingRef.current = false; | ||
} | ||
}, [auth, clearRefreshTimeout]); | ||
|
||
const refresh = useCallback(async () => { | ||
nicknisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (fetchingRef.current || !auth) { | ||
return; | ||
} | ||
|
||
fetchingRef.current = true; | ||
dispatch({ type: "FETCH_START" }); | ||
|
||
try { | ||
// The authkit-js client handles token refresh internally | ||
const token = await auth.getAccessToken(); | ||
|
||
dispatch({ type: "FETCH_SUCCESS", token }); | ||
|
||
if (token) { | ||
const tokenData = parseToken(token); | ||
if (tokenData) { | ||
const delay = getRefreshDelay(tokenData.timeUntilExpiry); | ||
clearRefreshTimeout(); | ||
refreshTimeoutRef.current = setTimeout(updateToken, delay); | ||
} | ||
} | ||
|
||
return token; | ||
} catch (error) { | ||
const typedError = | ||
error instanceof Error ? error : new Error(String(error)); | ||
dispatch({ type: "FETCH_ERROR", error: typedError }); | ||
refreshTimeoutRef.current = setTimeout( | ||
updateToken, | ||
RETRY_DELAY_SECONDS * 1000, | ||
); | ||
} finally { | ||
fetchingRef.current = false; | ||
} | ||
}, [auth, clearRefreshTimeout, updateToken]); | ||
|
||
useEffect(() => { | ||
if (!user) { | ||
dispatch({ type: "RESET" }); | ||
clearRefreshTimeout(); | ||
return; | ||
} | ||
updateToken(); | ||
|
||
return clearRefreshTimeout; | ||
}, [userId, updateToken, clearRefreshTimeout]); | ||
|
||
return { | ||
accessToken: state.token, | ||
loading: state.loading, | ||
error: state.error, | ||
refresh, | ||
}; | ||
} | ||
|
||
type TokenClaims<T> = Partial<JWTPayload & T>; | ||
|
||
/** | ||
* Extracts token claims from the access token. | ||
* | ||
* @example | ||
* ```ts | ||
* const { customClaim } = useTokenClaims<{ customClaim: string }>(); | ||
* console.log(customClaim); | ||
* ``` | ||
* | ||
* @return The token claims as a record of key-value pairs. | ||
*/ | ||
export function useTokenClaims<T = Record<string, unknown>>(): TokenClaims<T> { | ||
const { accessToken } = useAccessToken(); | ||
|
||
return useMemo(() => { | ||
if (!accessToken) { | ||
return {}; | ||
} | ||
|
||
try { | ||
return getClaims<T>(accessToken); | ||
} catch { | ||
return {}; | ||
} | ||
}, [accessToken]); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export { useAccessToken, useTokenClaims } from "./accessToken"; | ||
export { useAuth } from "./hook"; | ||
export { AuthKitProvider } from "./provider"; | ||
export { getClaims } from "@workos-inc/authkit-js"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the traditional way to get claims in authkit-react is via the
useAuth
hook. i think we should just extend that to support custom claims instead of bolting on a new hook.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So, I was looking to bring closer parity to authkit-nextjs, having the same hooks in workos/authkit-nextjs#258 plus having a cleaner separation of concerns.