# Web Worker Client

Triplit supports running the client in a Web Worker (specifically, a [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker), which can connect to multiple tabs running a script from the same domain). While running a Web Worker, data syncs between browser tabs without having to sync with server. This reduces network traffic for Triplit apps running in the multiple tabs, move Triplit local database computation to a separate thread, and allow for robust multi-tab offline support.

## `WorkerClient`

The `WorkerClient` is a drop-in replacement for the `TriplitClient` that runs in a Web Worker. It provides the same API as the `TriplitClient`. To use it, import `WorkerClient` from `@triplit/client/worker-client` and create a new instance of the client:

```ts copy
import { WorkerClient } from '@triplit/client/worker-client';
import { schema } from './schema';

const client = new WorkerClient({
  schema,
  serverUrl: import.meta.env.VITE_TRIPLIT_SERVER_URL,
  token: import.meta.env.VITE_TRIPLIT_TOKEN,
});
```

### With Vite

To use it in [Vite](https://vitejs.dev), you need to import an additional parameter `workerUrl`, which helps the Vite build process to correctly bundle the Web Worker:

```ts {3,6} copy
import { WorkerClient } from '@triplit/client/worker-client';
import { schema } from './schema';
import workerUrl from '@triplit/client/worker-client-operator?url';

const client = new WorkerClient({
  workerUrl,
  schema,
  serverUrl: import.meta.env.VITE_TRIPLIT_SERVER_URL,
  token: import.meta.env.VITE_TRIPLIT_TOKEN,
});
```

**However**, some frameworks, including [SvelteKit](https://kit.svelte.dev), use Vite for development but use platform specific plugins that bundle differently for production. If you encounter issues with the `WorkerClient` in production, try removing the `workerUrl` parameter.

Here's an example of how to use the `WorkerClient` in SvelteKit when deploying to Vercel that works in both development and production:

```ts {6} copy
import { browser, dev } from '$app/environment';
import { schema } from '../../triplit/schema';
import workerUrl from '@triplit/client/worker-client-operator?url';

export const triplit = new WorkerClient({
  workerUrl: dev ? workerUrl : undefined,
  schema,
  token: PUBLIC_TRIPLIT_TOKEN,
  serverUrl: PUBLIC_TRIPLIT_SERVER_URL,
  autoConnect: browser,
});
```

## Debugging a `WorkerClient`

Because the `WorkerClient` runs in a Shared Worker you can't immediately view the Triplit-specific logs it produces. Instead, navigate to `chrome://inspect/#workers` to view the logs for the Shared Worker. We plan to add better debugging support for the `WorkerClient` in the future.
