Shared state in .svelte.ts modules

By Esteban Trillo7 min readWhy SvelteSvelte

The cart can live in the shared box. The signed-in user goes in a box made for this request.
The cart can live in the shared box. The signed-in user goes in a box made for this request.

Part 8 of a series on Svelte in 2026. Part 7 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:

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:

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.1 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.

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();
Header.svelte
<script lang="ts">
import { cart } from "./cart.svelte";
</script>
<header>{cart.items.length} items, ${cart.total}</header>
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:

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:

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.1 Svelte refuses to compile that:

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:

The module exports…
The compiler
Refuses: state_invalid_export. "Either export a function returning the state value or only mutate the state value's properties."
Importer
Never gets that far.
The compiler
Compiles it to export let count = 0. Nothing writes it, so there's nothing to track.
Importer
A plain 0, forever.
The compiler
Compiles it to $.proxy({ count: 0 }). The binding never changes; its properties do.
Importer
Reads counter.count and updates when it changes: 0, then 2 after two clicks.
The compiler
Refuses: derived_invalid_export. "Export a function returning its value."
Importer
Never gets that far.
The compiler
Keeps count as $.state(0) and compiles the body to return $.get(count).
Importer
Calls getCount() in the template and updates: 0, then 2.
The compiler
Turns each field into a private signal plus a get/set pair on the class.
Importer
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.”2

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?

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.3

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:

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.”3

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.4

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>();
+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.”2 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.

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.”5 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.6

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 covers the two export options in a few lines.1 Read the context page for createContext and its “Replacing global state” section, and SvelteKit’s state management page for what shared state does on a server.3

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

Footnotes

  1. Svelte docs, $state: Passing state across modules. ↩ ↩2 ↩3

  2. Svelte docs, Best practices. ↩ ↩2

  3. SvelteKit docs, State management: Avoid shared state on the server. ↩ ↩2 ↩3

  4. Svelte changelog, 5.40.0: “add createContext utility for type-safe context” (#16948). ↩

  5. React docs, useSyncExternalStore. ↩

  6. Svelte docs, $effect.root. ↩

Read next

  1. Svelte best practices from the docs, testedNov 29, 2026 Why Svelte · 7 min
  2. Built-in transitions and animationsNov 29, 2026 Why Svelte · 8 min
  3. In Svelte 5, children is a functionNov 28, 2026 Why Svelte · 6 min
  4. A Svelte prop is a getter, not an argumentNov 28, 2026 Why Svelte · 7 min
  5. Scoped styles: CSS that stays putNov 30, 2026 Why Svelte · 9 min
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.