# Shared state in .svelte.ts modules

- Published: 2026-11-29
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-8-shared-state-in-svelte-ts-modules/

> Part 8 of a series on Svelte in 2026. [Part 7](/writing/why-svelte-7-children-is-a-function/) covered snippets. This part leaves the component file and puts state where any component can import it.

I put one line in a file called `counter.ts`:

```ts title="counter.ts"
export const counter = $state({ count: 0 });
```

TypeScript accepted it. So did svelte-check 4.7.7: `0 ERRORS 0 WARNINGS`. Then I imported it and ran it:

```txt
ReferenceError: $state is not defined
```

Rename the file to `counter.svelte.ts` and the same line works, and every component that imports `counter` sees the same object and updates when it changes. That's shared state in Svelte 5, with no store library and no `writable()`. The file name is the whole trick, and every rule below follows from it.

## Runes only exist where the compiler looks

Part 2 said runes compile only in `.svelte`, `.svelte.js` and `.svelte.ts` files.[^state] Here's the part that bites. `$state` isn't a function you import; Svelte declares it as a global type so your editor knows it, and the compiler replaces it before your code ever runs. A plain `.ts` file never goes through the Svelte compiler, so nothing replaces it, and at runtime there's no `$state` to call. The types say it exists, which is why TypeScript has no complaint.

With the `.svelte.ts` suffix, the module goes through `compileModule`, and the line comes out as `export const counter = $.proxy({ count: 0 })`, the deep proxy from part 3. Everything that imports `counter` gets the same proxy, so it's shared.

## A cart with no store

Here's something closer to real code: a cart that a header reads and a product button writes.

```ts title="cart.svelte.ts"
type Item = { name: string; price: number };

class Cart {
  items = $state<Item[]>([]);
  total = $derived(this.items.reduce((sum, i) => sum + i.price, 0));

  add(item: Item) {
    this.items.push(item);
  }
}

export const cart = new Cart();
```

```svelte title="Header.svelte"
<script lang="ts">
  import { cart } from "./cart.svelte";
</script>

<header>{cart.items.length} items, ${cart.total}</header>
```

```svelte title="Product.svelte"
<script lang="ts">
  import { cart } from "./cart.svelte";
  let { name, price }: { name: string; price: number } = $props();
</script>

<button onclick={() => cart.add({ name, price })}>Add {name}</button>
```

The import path is `./cart.svelte`. The docs write `./state.svelte.js`, and svelte-check resolved that form to the `.ts` file too, types included. I mounted a page with one header and two products and clicked each button:

```txt
mount              0 items, $0
click mug          1 items, $12
click tee          2 items, $32
plain.ts add       3 items, $32
```

The fourth line is a plain `.ts` file calling `cart.add()` for a free sticker. The header updated. That file can't _declare_ state, but it can use state somebody else declared, because the reactive part was compiled into `cart.svelte.ts`. The compiled class shows how:

```js title="cart.svelte.js (compiled, excerpt)"
class Cart {
  #items = $.state($.proxy([]));
  get items() {
    return $.get(this.#items);
  }
  #total = $.derived(() => this.items.reduce((sum, i) => sum + i.price, 0));
  get total() {
    return $.get(this.#total);
  }
}
```

Each field became a private signal and a getter. The importer never sees a signal. It reads `cart.total`, and the getter calls `$.get` inside the module, where the compiler already did its work. Part 6 found getters in the props object. It's the same move across a file boundary.

## What you can't export

The compiler handles one file at a time. Inside the module that declares `let count = $state(0)`, it rewrites every `count` to `$.get(count)` and every `count = …` to `$.set(…)`. A file that imports `count` was compiled separately and gets no rewrite, so it would read the signal object itself instead of the number.[^state] Svelte refuses to compile that:

```txt
state_invalid_export: Cannot export state from a module if it is reassigned.
Either export a function returning the state value or only mutate the state
value's properties
```

`$derived` gets the same treatment: `export const doubled = $derived(n * 2)` fails with `derived_invalid_export`. And there's a quiet case. `export let count = $state(0)` that nothing reassigns compiles fine, to `export let count = 0`. A plain number. Since nobody writes it, nobody needs to hear about it changing, and Svelte drops the rune.

So the export has to be something the compiler can carry across. Pick one:

**What crosses the file boundary?** The module exports…

| The module exports | The compiler | A component that imports it |
| --- | --- | --- |
| export let count = $state(0), reassigned by increment() | Refuses: state_invalid_export. "Either export a function returning the state value or only mutate the state value's properties." | Never gets that far. |
| export let count = $state(0), never reassigned | Compiles it to export let count = 0. Nothing writes it, so there's nothing to track. | A plain 0, forever. |
| export const counter = $state({ count: 0 }), mutated | Compiles it to $.proxy({ count: 0 }). The binding never changes; its properties do. | Reads counter.count and updates when it changes: 0, then 2 after two clicks. |
| export const doubled = $derived(n * 2) | Refuses: derived_invalid_export. "Export a function returning its value." | Never gets that far. |
| export function getCount() { return count } | Keeps count as $.state(0) and compiles the body to return $.get(count). | Calls getCount() in the template and updates: 0, then 2. |
| export const cart = new Cart(), with $state and $derived fields | Turns each field into a private signal plus a get/set pair on the class. | Reads cart.items and cart.total like plain properties, and both update. |

I lean on the class. It reads like the object version, it holds `$derived` fields, which a module can't export on its own, and the methods sit next to the state they change. Svelte's best-practices page says the same: "use classes with `$state` fields to share reactivity between components, instead of using stores."[^best]

**Quiz:** The cart holds a $12 mug. A component does const { total } = cart in its script and renders {total}. Then someone adds a $20 tee. What does the component show?

- 32
- 12
- A compile error

**Answer:** 12 — In the lab, the destructured total stayed at 12 while {cart.total} next to it went to 32. Read cart.total where you use it.

- Not "32": That's what cart.total says. Destructuring called the getter once and copied the number out, so the component holds 12, not a link to cart.total.
- Not "A compile error": Nothing stops you. Svelte compiled the destructure with no error and no warning.

## The server shares the module too

Here's the gotcha that matters most, because it leaks data instead of throwing. A module is evaluated once per process. In the browser, a process is one tab for one user. On a server doing SSR, it's every request from every user.[^kit]

I made a `session.svelte.ts` holding `$state({ user: "" })`, a page that prints `Signed in as {session.user || "nobody"}`, and a request handler that sets `session.user` when someone's signed in. Then I rendered it on the server twice, once for Ada and once for an anonymous visitor:

```txt
module  req 1 (ada):  <p>Signed in as ada</p>
module  req 2 (anon): <p>Signed in as ada</p>
```

The anonymous visitor got Ada's name. Nothing warned. SvelteKit's docs make the same point with a form action writing to a module-level `user`: "The user variable is shared by everyone who connects to this server."[^kit]

The fix is to make one instance per request and hand it down the tree with context. Since 5.40.0, `createContext` gives you a typed getter and setter pair.[^changelog]

```ts title="session.svelte.ts"
import { createContext } from "svelte";

type Data = { user: string };

export class Session {
  #data: () => Data;
  user = $derived.by(() => this.#data().user);

  constructor(data: () => Data) {
    this.#data = data;
  }
}

export const [getSession, setSession] = createContext<Session>();
```

```svelte title="+layout.svelte"
<script lang="ts">
  import { Session, setSession } from "./session.svelte";
  let { data, children } = $props();
  setSession(new Session(() => data));
</script>

{@render children()}
```

Any component below the layout calls `getSession()`. The class takes a function instead of `data` itself, for the reason part 6 gave: `new Session(data.user)` reads the prop once, and Svelte warns `state_referenced_locally`. With a getter, the session follows `data` when it changes. In the lab, the same two requests rendered `ada` and then `nobody`, and on the client, swapping `data` for Grace's updated the badge to `grace`. A component that calls `getSession()` with no layout above it throws `missing_context`.

Svelte's best-practices page puts it bluntly: "consider using context instead of declaring state in a shared module."[^best] If your app is client-only, a module is fine. If anything renders on a server, ask whether the state belongs to the app or to the person.

## How React does it

React has no place to put state outside a component. A plain module object works until you change it. I tried it in React 19.3.1: a header reading `plain.items.length` and a button pushing to it.

```txt
plain: 0 items | module has 1
store: 1 items
```

The array changed and the header didn't, because React re-renders when state it owns changes and it doesn't own that array. The second line is the same cart written as an external store: a `subscribe` function, a `getSnapshot` function, a `Set` of listeners and an immutable update, read through `useSyncExternalStore`, "a React Hook that lets you subscribe to an external store."[^sync] It works. It's also roughly the code Zustand and Redux exist to write for you, and most React apps install one of them instead.

Svelte 4 had the same answer in the box: `writable()`, `subscribe`, and a `$` prefix to auto-subscribe in components. Stores still work in Svelte 5. But a `.svelte.ts` module uses the same signals a component uses, so a store's subscribe plumbing has nothing left to add for plain shared values.

## Gotchas

**`$effect` at module level.** An effect needs an owner to tear it down, and a module has none. Calling a function that runs `$effect` outside a component threw `effect_orphan`: "`$effect` can only be used inside an effect (e.g. during component initialisation)." `$effect.root` creates its own owner and returns a cleanup; mine logged `save light`, `save dark`, then stopped after I called it.[^effect]

**Classes don't survive `JSON.stringify`.** Part 3 found this in a component, and a shared cart hits it sooner: `JSON.stringify(cart)` gave `{}` on the client, because the fields are private and the getters live on the prototype. Add a `toJSON` method, or stringify `cart.items`.

**Holding on to a field.** `cart.items = []` is fine for anyone who reads `cart.items`, since the getter returns the new array. A component that saved `const items = cart.items` at the top of its script kept the old one: after the reset it still showed 2 items while the cart had 0. Same cause as the quiz, one level down.

## The module is the store

A Svelte 4 store was a small object with a subscribe method, and you needed it because a variable couldn't tell anyone it had changed. In Svelte 5 a variable can, as long as the compiler sees it. A `.svelte.ts` file gets compiled, so its state is the same kind of state a component has, and any file can import it. What you export has to keep the reads inside the module: a proxy you mutate, a function, or a class with getters. On the server, the module is global to every user, so per-user state goes in context.

The [`$state` page](https://svelte.dev/docs/svelte/$state#Passing-state-across-modules) covers the two export options in a few lines.[^state] Read the [context page](https://svelte.dev/docs/svelte/context) for `createContext` and its "Replacing global state" section, and SvelteKit's [state management](https://svelte.dev/docs/kit/state-management) page for what shared state does on a server.[^kit]

Next: what Svelte's own best-practices page tells you to do.

[^state]: Svelte docs, [`$state`: Passing state across modules](https://svelte.dev/docs/svelte/$state#Passing-state-across-modules).

[^best]: Svelte docs, [Best practices](https://svelte.dev/docs/svelte/best-practices).

[^kit]: SvelteKit docs, [State management: Avoid shared state on the server](https://svelte.dev/docs/kit/state-management#Avoid-shared-state-on-the-server).

[^changelog]: [Svelte changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md), 5.40.0: "add `createContext` utility for type-safe context" ([#16948](https://github.com/sveltejs/svelte/pull/16948)).

[^sync]: React docs, [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore).

[^effect]: Svelte docs, [`$effect.root`](https://svelte.dev/docs/svelte/$effect#$effect.root).

- **Part 9 — Svelte best practices from the docs, tested**: the official best-practices page, rule by rule: unkeyed lists, #key, window listeners, style props and the legacy list, run in a lab
