Skip to content
Draft
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 number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Reduce redundant native and JavaScript client refreshes during Expo startup.
Original file line number Diff line number Diff 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 Down Expand 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 Down Expand 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 number Diff line number Diff 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 Down Expand 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 Down Expand Up @@ -281,15 +295,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 @@ -305,6 +342,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 number Diff line number Diff 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 number Diff line number Diff 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 Down Expand 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 number Diff line number Diff 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 Down Expand 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