Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(clerk-expo): Introduce getClerkInstance to access/create a Clerk instance #3420

36 changes: 36 additions & 0 deletions .changeset/calm-wasps-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
'@clerk/clerk-expo': minor
---

Introduce `getClerkInstance()` to avoid importing the Clerk class from clerk-js manually.

This enables developers to create and access a Clerk instance in their application outside of React.
```tsx
import { ClerkProvider, getClerkInstance } from "@clerk/expo"

const clerkInstance = getClerkInstance({ publishableKey: 'xxxx' })

// Always pass the `publishableKey` to `ClerkProvider`
<ClerkProvider publishableKey={'xxxx'}>
...
</ClerkProvider>

// Somewhere in your code, outside of React you can do
const token = await clerkInstance.session?.getToken();
fetch('http://example.com/', {headers: {Authorization: token })
```
```tsx
import { ClerkProvider, getClerkInstance } from "@clerk/expo"

// Always pass the `publishableKey` to `ClerkProvider`
<ClerkProvider publishableKey={'xxxx'}>
...
</ClerkProvider>

// If you sure that this code will run after the ClerkProvider has rendered then you can use `getClerkIntance` without options
const token = await getClerkInstance().session?.getToken();
fetch('http://example.com/', {headers: {Authorization: token })

```
Attention: If `getClerkInstance` is called without a publishable key, and ClerkProvider has not rendered yet, an error will be thrown

14 changes: 6 additions & 8 deletions packages/expo/src/ClerkProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,25 @@ import { ClerkProvider as ClerkReactProvider } from '@clerk/clerk-react';
import React from 'react';

import type { TokenCache } from './cache';
import { MemoryTokenCache } from './cache';
import { isReactNative } from './runtime';
import { buildClerk } from './singleton';
import { getClerkInstance } from './singleton';

export type ClerkProviderProps = ClerkReactProviderProps & {
tokenCache?: TokenCache;
};

export function ClerkProvider(props: ClerkProviderProps): JSX.Element {
const { children, tokenCache = MemoryTokenCache, publishableKey, ...rest } = props;
const key =
publishableKey || process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY || process.env.CLERK_PUBLISHABLE_KEY || '';
const { children, tokenCache, publishableKey, ...rest } = props;
const pk = publishableKey || process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY || process.env.CLERK_PUBLISHABLE_KEY || '';

return (
<ClerkReactProvider
// Force reset the state when the provided key changes, this ensures that the provider does not retain stale state.
// See JS-598 for additional context.
key={key}
key={pk}
{...rest}
publishableKey={key}
Clerk={buildClerk({ key, tokenCache })}
publishableKey={pk}
Clerk={getClerkInstance({ publishableKey: pk, tokenCache })}
standardBrowser={!isReactNative()}
>
{children}
Expand Down
5 changes: 5 additions & 0 deletions packages/expo/src/errorThrower.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { buildErrorThrower } from '@clerk/shared/error';

const errorThrower = buildErrorThrower({ packageName: PACKAGE_NAME });

export { errorThrower };
4 changes: 4 additions & 0 deletions packages/expo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ export {

export { isClerkAPIResponseError, isEmailLinkError, isKnownError, isMetamaskError } from '@clerk/clerk-react/errors';

/**
* @deprecated Use `getClerkInstance()` instead.
*/
export { clerk as Clerk } from './singleton';
export { getClerkInstance } from './singleton';

export * from './ClerkProvider';
export * from './useOAuth';
Expand Down
50 changes: 39 additions & 11 deletions packages/expo/src/singleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Clerk } from '@clerk/clerk-js/headless';
import type { HeadlessBrowserClerk } from '@clerk/clerk-react';

import type { TokenCache } from './cache';
import { MemoryTokenCache } from './cache';
import { errorThrower } from './errorThrower';

Clerk.sdkMetadata = {
name: PACKAGE_NAME,
Expand All @@ -11,29 +13,56 @@ Clerk.sdkMetadata = {

const KEY = '__clerk_client_jwt';

/**
* @deprecated Use `getClerkInstance` instead. `Clerk` will be removed in the next major version.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙃 typo, clerk should be with lower case to match the actual export.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So i looked at this again, turns out the exported variable from the package is Clerk so the initial comment is correct

*/
export let clerk: HeadlessBrowserClerk;
let __internal_clerk: HeadlessBrowserClerk | undefined;

type BuildClerkOptions = {
key: string;
tokenCache: TokenCache;
publishableKey?: string;
tokenCache?: TokenCache;
};

export function buildClerk({ key, tokenCache }: BuildClerkOptions): HeadlessBrowserClerk {
/**
* Access or create a Clerk instance outside of React.
* @example
* import { ClerkProvider, getClerkInstance } from "@clerk/expo"
*
* const clerkInstance = getClerkInstance({ publishableKey: 'xxxx' })
*
* // Always pass the `publishableKey` to `ClerkProvider`
* <ClerkProvider publishableKey={'xxxx'}>
* ...
* </ClerkProvider>
*
* // Somewhere in your code, outside of React you can do
* const token = await clerkInstance.session?.getToken();
* fetch('http://example.com/', {headers: {Authorization: token })
* @throws MissingPublishableKeyError publishableKey is missing and Clerk has not been initialized yet
* @returns HeadlessBrowserClerk
*/
export function getClerkInstance(options?: BuildClerkOptions): HeadlessBrowserClerk {
const { publishableKey = process.env.CLERK_PUBLISHABLE_KEY || '', tokenCache = MemoryTokenCache } = options || {};

if (!__internal_clerk && !publishableKey) {
errorThrower.throwMissingPublishableKeyError();
}

// Support "hot-swapping" the Clerk instance at runtime. See JS-598 for additional details.
const hasKeyChanged = clerk && key !== clerk.publishableKey;
const hasKeyChanged = __internal_clerk && publishableKey !== __internal_clerk.publishableKey;

if (!clerk || hasKeyChanged) {
if (!__internal_clerk || hasKeyChanged) {
if (hasKeyChanged) {
tokenCache.clearToken?.(KEY);
}

const getToken = tokenCache.getToken;
const saveToken = tokenCache.saveToken;
// TODO: DO NOT ACCEPT THIS
clerk = new Clerk(key);
__internal_clerk = clerk = new Clerk(publishableKey);

// @ts-expect-error
clerk.__unstable__onBeforeRequest(async (requestInit: FapiRequestInit) => {
__internal_clerk.__unstable__onBeforeRequest(async (requestInit: FapiRequestInit) => {
// https://reactnative.dev/docs/0.61/network#known-issues-with-fetch-and-cookie-based-authentication
requestInit.credentials = 'omit';

Expand All @@ -44,13 +73,12 @@ export function buildClerk({ key, tokenCache }: BuildClerkOptions): HeadlessBrow
});

// @ts-expect-error
clerk.__unstable__onAfterResponse(async (_: FapiRequestInit, response: FapiResponse<unknown>) => {
__internal_clerk.__unstable__onAfterResponse(async (_: FapiRequestInit, response: FapiResponse<unknown>) => {
const authHeader = response.headers.get('authorization');
if (authHeader) {
await saveToken(KEY, authHeader);
}
});
}

return clerk;
return __internal_clerk;
}
Loading