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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); fix(expo): deduplicate native client startup requests by mikepitre · Pull Request #9140 · clerk/javascript · GitHub
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/calm-clients-start.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line numberDiff line numberDiff line change
Expand Up@@ -215,13 +215,15 @@ class ClerkExpoModule : Module() {

coroutineScope.launch {
try {
val normalizedBearerToken = bearerToken?.trim()?.takeIf { it.isNotEmpty() }

if (!Clerk.isInitialized.value) {
// First-time initialization — write the bearer token to SharedPreferences
// before initializing so the SDK boots with the correct client.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
context.getSharedPreferences("clerk_preferences", Context.MODE_PRIVATE)
.edit()
.putString("DEVICE_TOKEN", bearerToken)
.putString("DEVICE_TOKEN", normalizedBearerToken)
.apply()
}

Expand All@@ -248,7 +250,7 @@ class ClerkExpoModule : Module() {
}
// If a bearer token was provided, wait for native client state to hydrate
// before resolving the configure call.
if (!bearerToken.isNullOrEmpty()) {
if (normalizedBearerToken != null) {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
}
Expand All@@ -270,6 +272,7 @@ class ClerkExpoModule : Module() {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${error.message}", null)
} else {
configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
}
return@launch
Expand DownExpand Up@@ -303,10 +306,13 @@ class ClerkExpoModule : Module() {
return@launch
}

if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
if (clientState.deviceToken != normalizedBearerToken || clientState.client == null) {
val result = Clerk.updateDeviceToken(normalizedBearerToken)
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken after reconfigure failed: ${result.error}")
}
}

try {
Expand All@@ -319,17 +325,28 @@ class ClerkExpoModule : Module() {
}

configuredPublishableKey = pubKey
lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
return@launch
}

// Already initialized — use the public SDK API to update
// the device token and trigger a client/environment refresh.
startClientStateObserver()
if (!bearerToken.isNullOrEmpty()) {
val result = Clerk.updateDeviceToken(bearerToken)
if (normalizedBearerToken != null) {
val clientState = clientStateSnapshot()
val result = if (
clientState.deviceToken != normalizedBearerToken ||
clientState.client == null
) {
Clerk.updateDeviceToken(normalizedBearerToken)
} else {
// A remounted JS runtime can have the same token while native
// client state is stale, so preserve one refresh in that case.
Clerk.refreshClient()
}
if (result is ClerkResult.Failure) {
debugLog(TAG, "configure - updateDeviceToken failed: ${result.error}")
debugLog(TAG, "configure - client refresh failed: ${result.error}")
}

// Wait for client state to hydrate with the new token (up to 5s).
Expand All@@ -342,6 +359,7 @@ class ClerkExpoModule : Module() {
}
}

lastObservedClientState = clientStateSnapshot()
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_INIT_FAILED", "Failed to initialize Clerk SDK: ${e.message}", e)
Expand DownExpand Up@@ -382,6 +400,7 @@ class ClerkExpoModule : Module() {
try {
jsOriginatedClientSyncDepth += 1
val previousClientState = clientStateSnapshot()
var refreshedClientWhileUpdatingToken = false

if (didChangeDeviceToken && !deviceToken.isNullOrBlank()) {
val currentDeviceToken = try {
Expand All@@ -401,6 +420,7 @@ class ClerkExpoModule : Module() {
return@launch
}
is ClerkResult.Success -> {
refreshedClientWhileUpdatingToken = true
try {
withTimeout(5_000L) {
Clerk.clientFlow.first { it != null }
Expand All@@ -413,7 +433,7 @@ class ClerkExpoModule : Module() {
}
}

if (didChangeClient || didChangeDeviceToken) {
if (!refreshedClientWhileUpdatingToken && (didChangeClient || didChangeDeviceToken)) {
when (val result = Clerk.refreshClient()) {
is ClerkResult.Failure -> {
promise.reject(
Expand Down
80 changes: 59 additions & 21 deletions packages/expo/ios/ClerkNativeBridge.swift
Original file line numberDiff line numberDiff line change
Expand Up@@ -48,6 +48,8 @@ final class ClerkNativeBridge {

private var clientObservationGeneration = 0
private var lastObservedClientState: ClientStateSnapshot?
private var configurationDepth = 0
private var jsOriginatedClientSyncDepth = 0

private init() {}

Expand All@@ -74,6 +76,12 @@ final class ClerkNativeBridge {

@MainActor
func configure(publishableKey: String, bearerToken: String? = nil) async throws {
configurationDepth += 1
defer {
lastObservedClientState = Self.clerkConfigured ? Self.clientStateSnapshot() : nil
configurationDepth = max(0, configurationDepth - 1)
}

loadThemes()

if Self.shouldReconfigure(for: publishableKey) {
Expand All@@ -84,16 +92,21 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
return
}

if Self.clerkConfigured {
startClientObserver()
let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
let didUpdateDeviceToken = try await Self.syncTokenState(bearerToken: bearerToken)
if didUpdateDeviceToken {
await Self.waitForLoadedClient()
} else if let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
// A remounted JS runtime can have the same token while native client
// state is stale, so preserve one refresh in that case.
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
return
}

Expand All@@ -104,16 +117,9 @@ final class ClerkNativeBridge {

let shouldWaitForClient = try await Self.syncTokenState(bearerToken: bearerToken)
await Self.waitForLoadedClientIfNeeded(shouldWaitForClient)
Self.emitClientChangedIfReceivedToken(bearerToken)
Self.postConfiguredNotification()
}

@MainActor
private static func emitClientChangedIfReceivedToken(_ bearerToken: String?) {
guard let token = bearerToken, !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
Self.emitClientChanged(Self.clientChangedPayload(changes: .init(client: false, deviceToken: true)))
}

@MainActor
private func startClientObserver(reset: Bool = false) {
guard reset || clientObservationGeneration == 0 else {
Expand All@@ -139,13 +145,15 @@ final class ClerkNativeBridge {
let newClientState = Self.clientStateSnapshot()
if let previousClientState = self.lastObservedClientState, newClientState != previousClientState {
self.lastObservedClientState = newClientState
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
if self.configurationDepth == 0, self.jsOriginatedClientSyncDepth == 0 {
let payload = Self.clientChangedPayload(
changes: .init(
client: newClientState.client != previousClientState.client,
deviceToken: newClientState.deviceToken != previousClientState.deviceToken
)
)
)
Self.emitClientChanged(payload)
Self.emitClientChanged(payload)
}
}

self.observeClient(generation: generation)
Expand DownExpand Up@@ -180,8 +188,14 @@ final class ClerkNativeBridge {

@MainActor
private static func syncTokenState(bearerToken: String?) async throws -> Bool {
guard let token = bearerToken, !token.isEmpty else {
return Clerk.shared.deviceToken != nil
await waitForLoadedClient()

guard let token = bearerToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
else {
return false
}
guard Clerk.shared.deviceToken != token || Clerk.shared.client == nil else {
return false
}
_ = try await Clerk.shared.updateDeviceToken(token)
return true
Expand DownExpand Up@@ -283,15 +297,38 @@ final class ClerkNativeBridge {
guard Self.clerkConfigured else { return }

let previousClientState = Self.clientStateSnapshot()
var completedSuccessfully = false
jsOriginatedClientSyncDepth += 1
defer {
let finalClientState = Self.clientStateSnapshot()
lastObservedClientState = finalClientState
jsOriginatedClientSyncDepth = max(0, jsOriginatedClientSyncDepth - 1)

if !completedSuccessfully, finalClientState != previousClientState {
Self.emitClientChanged(
Self.clientChangedPayload(
changes: .init(
client: finalClientState.client != previousClientState.client,
deviceToken: finalClientState.deviceToken != previousClientState.deviceToken
)
)
)
}
}

var refreshedClientWhileUpdatingToken = false

if didChangeDeviceToken, let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty {
if didChangeDeviceToken,
let token = deviceToken?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty
{
if Clerk.shared.deviceToken != token {
_ = try await Clerk.shared.updateDeviceToken(token)
await Self.waitForLoadedClient()
refreshedClientWhileUpdatingToken = true
}
}

if didChangeClient || didChangeDeviceToken {
if !refreshedClientWhileUpdatingToken, didChangeClient || didChangeDeviceToken {
_ = try await Clerk.shared.refreshClient()
await Self.waitForLoadedClient()
}
Expand All@@ -307,6 +344,7 @@ final class ClerkNativeBridge {
)
)
)
completedSuccessfully = true
}

private static func postConfiguredNotification() {
Expand Down
16 changes: 16 additions & 0 deletions packages/expo/src/hooks/__tests__/useNativeClientEvents.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,22 @@ describe('useNativeClientEvents', () => {
unmount();
});

test('subscribes only while native client events are enabled', () => {
const { rerender, unmount } = renderHook(({ enabled }) => useNativeClientEvents(enabled), {
initialProps: { enabled: false },
});

expect(mocks.moduleAddListener).not.toHaveBeenCalled();

rerender({ enabled: true });
expect(mocks.moduleAddListener).toHaveBeenCalledTimes(1);

rerender({ enabled: false });
expect(mocks.remove).toHaveBeenCalledTimes(1);

unmount();
});

test('does not subscribe modules without an Expo event emitter', () => {
mocks.nativeModule = {
configure: vi.fn(),
Expand Down
9 changes: 7 additions & 2 deletions packages/expo/src/hooks/useNativeClientEvents.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -54,10 +54,15 @@ function isNativeClientSnapshot(snapshot: NativeClientSnapshot | undefined): sna
/**
* Listens for native client events that should sync JS client state.
*/
export function useNativeClientEvents(): UseNativeClientEventsReturn {
export function useNativeClientEvents(enabled = true): UseNativeClientEventsReturn {
const [nativeClientEvent, setNativeClientEvent] = useState<NativeClientEvent | null>(null);

useEffect(() => {
if (!enabled) {
setNativeClientEvent(null);
return;
}

if (!isNativeSupported || !ClerkExpo) {
return;
}
Expand DownExpand Up@@ -87,7 +92,7 @@ export function useNativeClientEvents(): UseNativeClientEventsReturn {
return () => {
subscription?.remove();
};
}, []);
}, [enabled]);

return {
nativeClientEvent,
Expand Down
5 changes: 4 additions & 1 deletion packages/expo/src/provider/ClerkProvider.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -90,13 +90,15 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
: null;

const suppressJsClientChangedRef = useRef(0);
const isMountedRef = useNativeClientBootstrap({
const { isMountedRef, isNativeClientReady } = useNativeClientBootstrap({
publishableKey: pk,
nativeRefreshFromJsControllerRef,
suppressTokenCacheNotificationsRef,
tokenCache: syncableTokenCache,
clerkInstance,
});
useNativeClientEventSync({
enabled: isNativeClientReady,
clerkInstance,
isMountedRef,
nativeRefreshFromJsControllerRef,
Expand DownExpand Up@@ -134,6 +136,7 @@ export function ClerkProvider<TUi extends Ui = Ui>(props: ClerkProviderProps<TUi
>
{isNative() && (
<NativeClientSync
enabled={isNativeClientReady}
clerkInstance={clerkInstance}
nativeRefreshFromJsControllerRef={nativeRefreshFromJsControllerRef}
suppressJsClientChangedRef={suppressJsClientChangedRef}
Expand Down
Loading
Loading