Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/soft-pumpkins-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Keyless prompt revalidate environment on focus at most every 10 seconds.
5 changes: 3 additions & 2 deletions packages/clerk-js/src/ui/components/KeylessPrompt/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ const contentIdentifier = `${buttonIdentifierPrefix}-content`;

const _KeylessPrompt = (_props: KeylessPromptProps) => {
const [isExpanded, setIsExpanded] = useState(false);
const claimed = Boolean(useRevalidateEnvironment().authConfig.claimedAt);
const environment = useRevalidateEnvironment();
const claimed = Boolean(environment.authConfig.claimedAt);

const success = false;
const appName = useRevalidateEnvironment().displayConfig.applicationName;
const appName = environment.displayConfig.applicationName;

const isForcedExpanded = claimed || success || isExpanded;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { useClerk } from '@clerk/shared/react';
import { useEffect, useReducer } from 'react';
import { useEffect, useReducer, useRef } from 'react';

import type { Clerk } from '../../../core/clerk';
import type { Environment } from '../../../core/resources';
import { useEnvironment } from '../../contexts';

const THROTTLE_DURATION_MS = 10 * 1000;

/**
* Revalidates environment on focus, highly optimized for Keyless mode.
* Attention: this is not a generic solution, and should not be used for revalidating environment inside UI components that are end-user facing (e.g. SignIn)
*/
function useRevalidateEnvironment() {
const clerk = useClerk();
const lastTouchTimestamp = useRef(Date.now());
const [, forceUpdate] = useReducer(v => v + 1, 0);

useEffect(() => {
Expand All @@ -29,6 +32,11 @@ function useRevalidateEnvironment() {
return controller.abort();
}

// Re-fetch at most every 10 seconds
if (Date.now() < lastTouchTimestamp.current + THROTTLE_DURATION_MS) {
return;
}

if (document.visibilityState !== 'visible') {
return;
}
Expand All @@ -39,6 +47,7 @@ function useRevalidateEnvironment() {
const {
authConfig: { claimedAt },
} = await environment.fetch();
lastTouchTimestamp.current = Date.now();

if (claimedAt !== null) {
forceUpdate();
Expand Down
Loading