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
8 changes: 8 additions & 0 deletions .changeset/client-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'convex-svelte': patch
---

### Fixes

- **No WebSocket during server rendering** - the client created by `setupConvex()` / `initConvex()` is now always disabled on the server, even when a caller passes `disabled: false`. Whether code runs on the server is decided at runtime (`typeof document`) instead of by the bundler's resolution of `esm-env`.
- **Ignored client options are reported** - client options only take effect where the shared client is created, like the `ConvexReactClient` constructor in React. When `setupConvex()` or a repeated `initConvex()` passes options that differ from the ones the client was created with (e.g. `expectAuth` in the root layout while `initConvex()` in `hooks.ts` created the client), a dev warning now names them instead of dropping them silently. Only primitive options are compared; functions and objects such as `logger` get a new identity on every hot reload.
9 changes: 7 additions & 2 deletions src/lib/client.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import { parseArgsWithSkip } from './internal/args.svelte.js';
import {
getConvexClient,
getSingletonClient,
getSingletonOptions,
getSingletonUrl,
setSingleton,
flushDeferredSubscriptions
} from './internal/singleton.js';
import { warnIgnoredOptions, withServerDisabled } from './internal/client_options.js';
import { isClientActive } from './internal/client_status.js';

const _contextKey = '$$_convexClient';
Expand Down Expand Up @@ -54,9 +56,12 @@ export const setupConvex = (url: string, options: ConvexClientOptions = {}): Con
'Only one deployment per app is supported. Call closeConvex() first to switch deployments.'
);
}
const client = existing ?? new ConvexClient(url, { disabled: !BROWSER, ...options });
if (existing) {
warnIgnoredOptions('setupConvex', getSingletonOptions(), options);
}
const client = existing ?? new ConvexClient(url, withServerDisabled(options));
if (!existing) {
setSingleton(url, client);
setSingleton(url, client, options);
}

setConvexClientContext(client);
Expand Down
93 changes: 93 additions & 0 deletions src/lib/internal/client_options.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

const env = vi.hoisted(() => ({ dev: true }));
vi.mock('esm-env', () => ({
get DEV() {
return env.dev;
}
}));

import { differingOptions, warnIgnoredOptions, withServerDisabled } from './client_options.js';

/** Run with or without a `document`, i.e. as in the browser or on the server. */
function inBrowser(browser: boolean) {
if (browser) globalThis.document = {} as Document;
else delete (globalThis as { document?: Document }).document;
}

afterEach(() => {
env.dev = true;
delete (globalThis as { document?: Document }).document;
vi.restoreAllMocks();
});

describe('withServerDisabled', () => {
it('always disables the client on the server, even with disabled: false', () => {
inBrowser(false);

expect(withServerDisabled({})).toEqual({ disabled: true });
expect(withServerDisabled({ disabled: false, verbose: true })).toEqual({
disabled: true,
verbose: true
});
});

it('enables the client in the browser unless disabled: true is passed', () => {
inBrowser(true);

expect(withServerDisabled({})).toEqual({ disabled: false });
expect(withServerDisabled({ disabled: true })).toEqual({ disabled: true });
});
});

describe('differingOptions', () => {
it('reports primitive options that differ from the creation options', () => {
expect(differingOptions({ verbose: true }, { verbose: true, expectAuth: true })).toEqual([
'expectAuth'
]);
expect(differingOptions({ expectAuth: true }, { expectAuth: false })).toEqual(['expectAuth']);
});

it('ignores disabled, functions and objects (new identity on every hot reload)', () => {
expect(
differingOptions(
{},
{
disabled: false,
logger: { logVerbose() {} } as never,
webSocketConstructor: class {} as never
}
)
).toEqual([]);
});
});

describe('warnIgnoredOptions', () => {
it('warns in the browser during development, naming the ignored options', () => {
inBrowser(true);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});

warnIgnoredOptions('setupConvex', {}, { expectAuth: true });

expect(warn).toHaveBeenCalledOnce();
expect(warn.mock.calls[0][0]).toContain('setupConvex(): ');
expect(warn.mock.calls[0][0]).toContain('ignored: expectAuth');
});

it('stays quiet for matching options, on the server, and in production', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});

inBrowser(true);
warnIgnoredOptions('initConvex', { expectAuth: true }, { expectAuth: true });
warnIgnoredOptions('initConvex', { expectAuth: true }, {});

inBrowser(false);
warnIgnoredOptions('initConvex', {}, { expectAuth: true });

inBrowser(true);
env.dev = false;
warnIgnoredOptions('initConvex', {}, { expectAuth: true });

expect(warn).not.toHaveBeenCalled();
});
});
60 changes: 60 additions & 0 deletions src/lib/internal/client_options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Options of the shared ConvexClient.
*
* Like `new ConvexReactClient(url, options)` in React, client options can only
* take effect where the client is created: `initConvex()` (SvelteKit, in
* `hooks.ts`) or the first `setupConvex()`. Later calls reuse the client, so
* options they pass are reported instead of silently dropped.
*/
import { DEV } from 'esm-env';
import type { ConvexClientOptions } from 'convex/browser';

const isServer = () => typeof globalThis.document === 'undefined';

/**
* Options for a new client. On the server the client is always disabled, so
* server rendering never opens a WebSocket — even if a caller passes
* `disabled: false`. Decided at runtime rather than by build-time conditions,
* so it can't go wrong with how a bundler resolves packages.
*/
export function withServerDisabled(options: ConvexClientOptions): ConvexClientOptions {
return { ...options, disabled: isServer() || options.disabled === true };
}

/**
* Names of `requested` options that differ from the ones the client was
* created with. Only primitive values are compared: functions and objects
* (e.g. `logger`) get a new identity on every hot reload. `disabled` is
* managed by convex-svelte.
*/
export function differingOptions(
created: ConvexClientOptions,
requested: ConvexClientOptions
): string[] {
return Object.entries(requested)
.filter(([name, value]) => {
if (name === 'disabled' || (typeof value === 'object' && value !== null)) return false;
if (typeof value === 'function') return false;
return created[name as keyof ConvexClientOptions] !== value;
})
.map(([name]) => name);
}

/**
* Dev only, in the browser (where the options matter): report options that a
* call passed for a client that already exists.
*/
export function warnIgnoredOptions(
caller: 'setupConvex' | 'initConvex',
created: ConvexClientOptions,
requested: ConvexClientOptions
): void {
if (!DEV || isServer()) return;
const ignored = differingOptions(created, requested);
if (ignored.length === 0) return;
console.warn(
`[convex-svelte] ${caller}(): the Convex client already exists, so these options are ` +
`ignored: ${ignored.join(', ')}. Client options only take effect where the client is ` +
'created, e.g. initConvex(url, options) in src/hooks.ts.'
);
}
18 changes: 16 additions & 2 deletions src/lib/internal/singleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
*
* This avoids a circular dependency between core and sveltekit.
*/
import type { ConvexClient } from 'convex/browser';
import type { ConvexClient, ConvexClientOptions } from 'convex/browser';

let _singletonClient: ConvexClient | null = null;
let _singletonUrl: string | null = null;
// Options the singleton was created with (see client_options.ts).
let _singletonOptions: ConvexClientOptions = {};

// ---------------------------------------------------------------------------
// Deferred subscription queue for transport.decode → setupAuth coordination.
Expand Down Expand Up @@ -84,6 +86,7 @@ export function getSingletonClient(): ConvexClient | null {
if (_singletonClient?.closed) {
_singletonClient = null;
_singletonUrl = null;
_singletonOptions = {};
return null;
}
return _singletonClient;
Expand All @@ -105,6 +108,7 @@ export async function closeConvex(): Promise<void> {
const client = _singletonClient;
_singletonClient = null;
_singletonUrl = null;
_singletonOptions = {};
// Restore defer mode so the next init cycle coordinates with setupAuth
// again instead of firing subscriptions immediately.
_deferredSubscriptions = [];
Expand All @@ -118,9 +122,19 @@ export function getSingletonUrl(): string | null {
return _singletonUrl;
}

export function setSingleton(url: string, client: ConvexClient): void {
/** Options the current client was created with. */
export function getSingletonOptions(): ConvexClientOptions {
return _singletonOptions;
}

export function setSingleton(
url: string,
client: ConvexClient,
options: ConvexClientOptions = {}
): void {
_singletonUrl = url;
_singletonClient = client;
_singletonOptions = options;
}

/**
Expand Down
8 changes: 8 additions & 0 deletions src/lib/sveltekit/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,12 @@ describe('initConvex — queryCache', () => {
verbose: true
});
});

it('keeps the client disabled on the server even when disabled: false is passed', () => {
initConvex('https://example.convex.cloud', { disabled: false });

expect(clientConstructed).toHaveBeenCalledWith('https://example.convex.cloud', {
disabled: true
});
});
});
17 changes: 12 additions & 5 deletions src/lib/sveltekit/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@
* - `setupConvex(url)` in root layout — handles context + cleanup, calls initConvex internally
*/
import { ConvexClient, type ConvexClientOptions } from 'convex/browser';
import { getSingletonClient, getSingletonUrl, setSingleton } from '../internal/singleton.js';
import {
getSingletonClient,
getSingletonOptions,
getSingletonUrl,
setSingleton
} from '../internal/singleton.js';
import { warnIgnoredOptions, withServerDisabled } from '../internal/client_options.js';
import { configureQueryCache, type QueryCacheOptions } from './query-lifecycle.js';

const IS_BROWSER = typeof globalThis.document !== 'undefined';

export type InitConvexOptions = ConvexClientOptions & {
/**
* Idle buffer for queries created by `convexLoad()` / `convexLoadPaginated()`.
Expand All @@ -27,6 +31,8 @@ export type InitConvexOptions = ConvexClientOptions & {
* Initialize the Convex client at module level (before any component mounts).
* Call from `hooks.client.ts` to ensure the client exists before `transport.decode`.
* Idempotent — subsequent calls with the same URL return the existing client.
* Client options only apply when the client is created (like the
* `ConvexReactClient` constructor); later calls with different ones warn in dev.
* A `queryCache` option is still applied, so editing it in `hooks.ts` takes
* effect on HMR.
*
Expand All @@ -53,9 +59,10 @@ export function initConvex(url: string, options: InitConvexOptions = {}): Convex
configureQueryCache(queryCache);
}
if (existing) {
warnIgnoredOptions('initConvex', getSingletonOptions(), clientOptions);
return existing;
}
const client = new ConvexClient(url, { disabled: !IS_BROWSER, ...clientOptions });
setSingleton(url, client);
const client = new ConvexClient(url, withServerDisabled(clientOptions));
setSingleton(url, client, clientOptions);
return client;
}
Loading