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
6 changes: 6 additions & 0 deletions .changeset/salty-ravens-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
---

Add the experimental cross-tab session sync proof of concept behind a dev-only flag, including worker lifecycle safeguards, automatic fallbacks, and metric hooks for observability.

1 change: 1 addition & 0 deletions packages/clerk-js/bundlewatch.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"files": [
{ "path": "./dist/clerk.js", "maxSize": "840KB" },
{ "path": "./dist/clerk.browser.js", "maxSize": "81KB" },
{ "path": "./dist/clerk.experimental.browser.js", "maxSize": "95KB" },
{ "path": "./dist/clerk.channel.browser.js", "maxSize": "81KB" },
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "123KB" },
{ "path": "./dist/clerk.headless*.js", "maxSize": "65KB" },
Expand Down
1 change: 1 addition & 0 deletions packages/clerk-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"dev": "rspack serve --config rspack.config.js",
"dev:channel": "rspack serve --config rspack.config.js --env variant=\"clerk.channel.browser\"",
"dev:chips": "rspack serve --config rspack.config.js --env variant=\"clerk.chips.browser\"",
"dev:experimental": "rspack serve --config rspack.config.js --env variant=\"clerk.experimental.browser\"",
"dev:headless": "rspack serve --config rspack.config.js --env variant=\"clerk.headless.browser\"",
"dev:origin": "rspack serve --config rspack.config.js --env devOrigin=http://localhost:${PORT:-4000}",
"dev:sandbox": "rspack serve --config rspack.config.js --env devOrigin=http://localhost:${PORT:-4000} --env sandbox=1",
Expand Down
91 changes: 66 additions & 25 deletions packages/clerk-js/rspack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,28 @@ const isDevelopment = mode => !isProduction(mode);

const variants = {
clerk: 'clerk',
clerkNoRHC: 'clerk.no-rhc', // Omit Remotely Hosted Code
clerkBrowser: 'clerk.browser',
clerkBrowserNoRHC: 'clerk.browser.no-rhc',
clerkCHIPS: 'clerk.chips.browser',
clerkChannelBrowser: 'clerk.channel.browser',
clerkExperimentalBrowser: 'clerk.experimental.browser',
clerkHeadless: 'clerk.headless',
clerkHeadlessBrowser: 'clerk.headless.browser',
clerkLegacyBrowser: 'clerk.legacy.browser',
clerkCHIPS: 'clerk.chips.browser',
clerkChannelBrowser: 'clerk.channel.browser',
clerkNoRHC: 'clerk.no-rhc', // Omit Remotely Hosted Code
};

const variantToSourceFile = {
[variants.clerk]: './src/index.ts',
[variants.clerkNoRHC]: './src/index.ts',
[variants.clerkBrowser]: './src/index.browser.ts',
[variants.clerkBrowserNoRHC]: './src/index.browser.ts',
[variants.clerkCHIPS]: './src/index.browser.ts',
[variants.clerkChannelBrowser]: './src/index.browser.ts',
[variants.clerkExperimentalBrowser]: './src/index.browser.ts',
[variants.clerkHeadless]: './src/index.headless.ts',
[variants.clerkHeadlessBrowser]: './src/index.headless.browser.ts',
[variants.clerkLegacyBrowser]: './src/index.legacy.browser.ts',
[variants.clerkCHIPS]: './src/index.browser.ts',
[variants.clerkChannelBrowser]: './src/index.browser.ts',
[variants.clerkNoRHC]: './src/index.ts',
};

/**
Expand All @@ -52,16 +56,17 @@ const common = ({ mode, variant, disableRHC = false }) => {
},
plugins: [
new rspack.DefinePlugin({
__DEV__: isDevelopment(mode),
__PKG_VERSION__: JSON.stringify(packageJSON.version),
__PKG_NAME__: JSON.stringify(packageJSON.name),
__BUILD_DISABLE_RHC__: JSON.stringify(disableRHC),
/**
* Build time feature flags.
*/
__BUILD_FLAG_KEYLESS_UI__: isDevelopment(mode),
__BUILD_DISABLE_RHC__: JSON.stringify(disableRHC),
__BUILD_VARIANT_CHANNEL__: variant === variants.clerkChannelBrowser,
__BUILD_VARIANT_EXPERIMENTAL__: variant === variants.clerkExperimentalBrowser,
__BUILD_VARIANT_CHIPS__: variant === variants.clerkCHIPS,
__DEV__: isDevelopment(mode),
__PKG_NAME__: JSON.stringify(packageJSON.name),
__PKG_VERSION__: JSON.stringify(packageJSON.version),
}),
new rspack.EnvironmentPlugin({
CLERK_ENV: mode,
Expand Down Expand Up @@ -179,14 +184,37 @@ const svgLoader = () => {
};
};

/** @type { () => (import('@rspack/core').RuleSetRule) } */
const workerLoader = () => {
return {
test: /\.worker\.ts$/,
type: 'asset/source',
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
},
minify: {
compress: true,
mangle: true,
},
},
minify: true,
},
},
};
};

/** @type { (opts?: { targets?: string, useCoreJs?: boolean }) => (import('@rspack/core').RuleSetRule[]) } */
const typescriptLoaderProd = (
{ targets = packageJSON.browserslist, useCoreJs = false } = { targets: packageJSON.browserslist, useCoreJs: false },
) => {
return [
{
test: /\.(jsx?|tsx?)$/,
exclude: /node_modules/,
exclude: [/node_modules/, /\.worker\.ts$/],
use: {
loader: 'builtin:swc-loader',
options: {
Expand Down Expand Up @@ -244,7 +272,7 @@ const typescriptLoaderDev = () => {
return [
{
test: /\.(jsx?|tsx?)$/,
exclude: /node_modules/,
exclude: [/node_modules/, /\.worker\.ts$/],
loader: 'builtin:swc-loader',
options: {
jsc: {
Expand Down Expand Up @@ -277,7 +305,7 @@ const commonForProdChunked = (
) => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderProd({ targets, useCoreJs })],
rules: [workerLoader(), svgLoader(), ...typescriptLoaderProd({ targets, useCoreJs })],
},
};
};
Expand All @@ -291,7 +319,7 @@ const commonForProdBundled = (
) => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderProd({ targets, useCoreJs })],
rules: [workerLoader(), svgLoader(), ...typescriptLoaderProd({ targets, useCoreJs })],
},
};
};
Expand Down Expand Up @@ -392,6 +420,13 @@ const prodConfig = ({ mode, env, analysis }) => {
commonForProdChunked(),
);

const clerkExperimentalBrowser = merge(
entryForVariant(variants.clerkExperimentalBrowser),
common({ mode, variant: variants.clerkExperimentalBrowser }),
commonForProd(),
commonForProdChunked(),
);

const clerkLegacyBrowser = merge(
entryForVariant(variants.clerkLegacyBrowser),
common({ mode, variant: variants.clerkLegacyBrowser }),
Expand Down Expand Up @@ -550,6 +585,7 @@ const prodConfig = ({ mode, env, analysis }) => {

return [
clerkBrowser,
clerkExperimentalBrowser,
clerkLegacyBrowser,
clerkHeadless,
clerkHeadlessBrowser,
Expand Down Expand Up @@ -581,7 +617,7 @@ const devConfig = ({ mode, env }) => {
const commonForDev = () => {
return {
module: {
rules: [svgLoader(), ...typescriptLoaderDev()],
rules: [workerLoader(), svgLoader(), ...typescriptLoaderDev()],
},
plugins: [
new ReactRefreshPlugin(/** @type {any} **/ ({ overlay: { sockHost: devUrl.host } })),
Expand Down Expand Up @@ -645,6 +681,21 @@ const devConfig = ({ mode, env }) => {
common({ mode, disableRHC: true, variant: variants.clerkBrowserNoRHC }),
commonForDev(),
),
[variants.clerkCHIPS]: merge(
entryForVariant(variants.clerkCHIPS),
common({ mode, variant: variants.clerkCHIPS }),
commonForDev(),
),
[variants.clerkChannelBrowser]: merge(
entryForVariant(variants.clerkChannelBrowser),
common({ mode, variant: variants.clerkChannelBrowser }),
commonForDev(),
),
[variants.clerkExperimentalBrowser]: merge(
entryForVariant(variants.clerkExperimentalBrowser),
common({ mode, variant: variants.clerkExperimentalBrowser }),
commonForDev(),
),
[variants.clerkHeadless]: merge(
entryForVariant(variants.clerkHeadless),
common({ mode, variant: variants.clerkHeadless }),
Expand All @@ -657,16 +708,6 @@ const devConfig = ({ mode, env }) => {
commonForDev(),
// externalsForHeadless(),
),
[variants.clerkCHIPS]: merge(
entryForVariant(variants.clerkCHIPS),
common({ mode, variant: variants.clerkCHIPS }),
commonForDev(),
),
[variants.clerkChannelBrowser]: merge(
entryForVariant(variants.clerkChannelBrowser),
common({ mode, variant: variants.clerkChannelBrowser }),
commonForDev(),
),
};

if (!entryToConfigMap[variant]) {
Expand Down
98 changes: 88 additions & 10 deletions packages/clerk-js/src/core/auth/AuthCookieService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,37 @@ import { createSessionCookie } from './cookies/session';
import { getCookieSuffix } from './cookieSuffix';
import type { DevBrowser } from './devBrowser';
import { createDevBrowser } from './devBrowser';
import { SessionCookiePoller } from './SessionCookiePoller';
import { SessionRefreshCoordinator } from './SessionRefreshCoordinator';

type CrossTabSyncOverride = 'disabled' | 'enabled';

const CROSS_TAB_SYNC_STORAGE_KEY = 'clerk:crossTabSessionSync';

const readCrossTabSyncOverride = (): CrossTabSyncOverride | null => {
if (typeof window === 'undefined') {
return null;
}

const override = (window as Window & { __clerkCrossTabSync?: CrossTabSyncOverride }).__clerkCrossTabSync;
if (override === 'enabled' || override === 'disabled') {
return override;
}

try {
const storedValue = window.localStorage?.getItem(CROSS_TAB_SYNC_STORAGE_KEY);
if (storedValue === 'enabled' || storedValue === 'disabled') {
return storedValue;
}
} catch (error) {
debugLogger.warn(
'AuthCookieService: Unable to read cross-tab sync preference from storage',
{ error },
'authCookieService',
);
}

return null;
};

// TODO(@dimkl): make AuthCookieService singleton since it handles updating cookies using a poller
// and we need to avoid updating them concurrently.
Expand All @@ -41,11 +71,12 @@ import { SessionCookiePoller } from './SessionCookiePoller';
* - handleUnauthenticatedDevBrowser(): resets dev browser in case of invalid dev browser
*/
export class AuthCookieService {
private poller: SessionCookiePoller | null = null;
private clientUat: ClientUatCookieHandler;
private sessionCookie: SessionCookieHandler;
private activeCookie: ReturnType<typeof createCookieHandler>;
private clientUat: ClientUatCookieHandler;
private crossTabSyncEnabled: boolean | null = null;
private devBrowser: DevBrowser;
private refreshCoordinator: SessionRefreshCoordinator | null = null;
private sessionCookie: SessionCookieHandler;

public static async create(
clerk: Clerk,
Expand Down Expand Up @@ -125,16 +156,18 @@ export class AuthCookieService {
}

public startPollingForToken() {
if (!this.poller) {
this.poller = new SessionCookiePoller();
this.poller.startPollingForSessionToken(() => this.refreshSessionToken());
if (!this.refreshCoordinator) {
this.refreshCoordinator = new SessionRefreshCoordinator();
this.refreshCoordinator.startPollingForSessionToken(() => this.refreshSessionToken(), {
enableEventDrivenSync: this.shouldUseCrossTabSessionSync(),
});
}
}

public stopPollingForToken() {
if (this.poller) {
this.poller.stopPollingForSessionToken();
this.poller = null;
if (this.refreshCoordinator) {
this.refreshCoordinator.stopPollingForSessionToken();
this.refreshCoordinator = null;
}
}

Expand Down Expand Up @@ -166,6 +199,13 @@ export class AuthCookieService {
if (updateCookieImmediately) {
this.updateSessionCookie(token);
}

if (this.refreshCoordinator?.isEventDriven()) {
const expiresAt = this.clerk.session.expireAt?.getTime() || null;
if (expiresAt) {
this.refreshCoordinator.notifyRefreshComplete(expiresAt);
}
}
} catch (e) {
return this.handleGetTokenError(e);
}
Expand All @@ -183,6 +223,13 @@ export class AuthCookieService {

this.setActiveContextInStorage();

if (this.refreshCoordinator?.isEventDriven()) {
const sessionId = this.clerk.session?.id || null;
const organizationId = this.clerk.organization?.id || null;
const expiresAt = this.clerk.session?.expireAt?.getTime() || null;
this.refreshCoordinator.updateSession({ expiresAt, organizationId, sessionId });
}

return token ? this.sessionCookie.set(token) : this.sessionCookie.remove();
}

Expand Down Expand Up @@ -222,6 +269,37 @@ export class AuthCookieService {
this.activeCookie.remove();
this.sessionCookie.remove();
this.setClientUatCookieForDevelopmentInstances();

if (this.refreshCoordinator?.isEventDriven()) {
this.refreshCoordinator.clearSession();
}
}

private determineCrossTabSessionSyncPreference(): boolean {
if (typeof window === 'undefined') {
return false;
}

const override = readCrossTabSyncOverride();
if (override === 'enabled') {
debugLogger.info('AuthCookieService: Cross-tab sync enabled via override', {}, 'authCookieService');
return true;
}

if (override === 'disabled') {
debugLogger.info('AuthCookieService: Cross-tab sync disabled via override', {}, 'authCookieService');
return false;
}

return __BUILD_VARIANT_EXPERIMENTAL__;
}

private shouldUseCrossTabSessionSync(): boolean {
if (this.crossTabSyncEnabled === null) {
this.crossTabSyncEnabled = this.determineCrossTabSessionSyncPreference();
}

return this.crossTabSyncEnabled;
}

/**
Expand Down
Loading