# Svelte

Source: https://verbaly.dev/docs/frameworks/svelte

The official Svelte 5 package for Verbaly. Idiomatic stores over the same reactive core, store factories for app-level use, and a \<Trans> component for rich text.

What you can accomplish:

- Translate with stores: `$t` re-renders on every language switch, no wiring
- Bind a language switcher in one line: `bind:value` on the language store just works
- Use context or store factories, with or without a component tree
- Map a tag in a message to your own component with the \<Trans> components prop

## Installation

Add the runtime, this package and the Vite plugin, then the compiler, which is where the `verbaly` command lives. `init` writes your config and your source catalog.

```sh
npm install verbaly @verbaly/svelte @verbaly/vite
# or: pnpm add verbaly @verbaly/svelte @verbaly/vite
# or: yarn add verbaly @verbaly/svelte @verbaly/vite
# or: bun add verbaly @verbaly/svelte @verbaly/vite
```

```sh
npm install -D @verbaly/compiler
# or: pnpm add -D @verbaly/compiler
# or: yarn add -D @verbaly/compiler
# or: bun add -D @verbaly/compiler
```

```sh
npx verbaly init
```

Then add `verbaly()` to the plugins in `vite.config`. It writes `verbaly/app`, the module your components read.

## Setup & stores

```svelte title="+layout.svelte · Inbox.svelte"
<script>
  // root component / layout:
  import { provideVerbaly } from '@verbaly/svelte';
  import { verbaly } from 'verbaly/app';
  provideVerbaly(verbaly);
</script>

<script>
  // any child component:
  import { useT, useLocale } from '@verbaly/svelte';
  const t = useT();
  const locale = useLocale();  // writable store
  const count = 3;
</script>

<p>{$t`You have ${count} messages`}</p>
<select bind:value={$locale}>…</select>
```

- Idiomatic stores: `$t` re-renders on every language switch; `bind:value={$locale}` on a select just works.
- No component tree? `tStore(instance)` / `localeStore(instance)` build the same stores without context, shared by the whole app.
- No `provideVerbaly` above a component, in the browser? `useT()` reads the instance `verbaly/app` creates, and the bundler plugin loads that module in every component that imports `@verbaly/svelte`, so a single-page app or a component test needs no wrapper. On a server a parent has to provide it, since each request has its own instance.

### The language a visitor picks

Setting `$locale` switches every component, and the page follows: `<html lang>`, `<html dir>` and the choice, saved in the browser. A single-page app starts in its source language, so read that choice back before mounting:

```ts title="main.ts"
// the saved choice, else the browser's, loaded before anything renders
import { mount } from 'svelte';
import { resolveLocale } from 'verbaly';
import { locales, setLocale } from 'verbaly/app';
import App from './App.svelte';

setLocale(resolveLocale({ supported: locales, path: false })).then(() =>
  mount(App, { target: document.getElementById('app')! }),
);
```

Where a server renders the page, as in SvelteKit, switch with `switchLocale` from `verbaly/app` instead: it also sets the cookie the server reads.

### Write the text in place

The compiler reads your `.svelte` files too: write the source text with the store tag, in a markup expression or in the script, and it is extracted, keyed and typed on save. Plain display text is never extracted, so a page can show `` t`…` `` as an example safely. No key to invent, no catalog to touch.

```svelte title="Inbox.svelte"
<h1>{$t`Hola ${name}, tienes ${count} mensajes`}</h1>

<!-- extracted on save; the build rewrites it to: -->
<h1>{$t('oHfbnDd4', { name, count })}</h1>
```

Prefer readable keys? `$t.id('inbox.title')` before the template extracts under your id instead of a content hash.

Prefer to keep the text in your catalog? Write only its key: it is checked and typed the same way. See [Keys and catalogs](https://verbaly.dev/docs/guide/keys.md).

### Rich text with \<Trans>

Svelte has its own component: import it from the `Trans.svelte` subpath (raw component, compiled by your bundler):

```svelte title="Title.svelte"
<script>
  import Trans from '@verbaly/svelte/Trans.svelte';
  import DocsLink from './DocsLink.svelte';
</script>

<Trans id='home.title' />
<Trans id='greet' values={{ name: 'Aron' }} />

<!-- message: 'Read the <docs>guide</docs>' → your component wraps the tag content -->
<Trans id='cta' components={{ docs: DocsLink }} />
```

- Message tags (`The <em>build</em> gate`) render as real elements from the same list of allowed tags as `data-verbaly-rich`. Unknown tags unwrap to inert text, `richTags` overrides.
- Uses the instance from `provideVerbaly`; pass `instance={verbaly}` explicitly when there's no context. Re-renders on every language switch.
- Named links: the `links` prop renders named tags as real `<a>` elements, with hrefs from your code, never from messages; `javascript:` blocked.
- Your own components: the `components` prop maps a tag to a Svelte component that receives the tag content as children, and wins over links and the allowed tags.

## SvelteKit

Server-rendered pages arrive already translated in the visitor's language, and the browser takes over with the same language and catalog: no flash of untranslated text, no mismatch between server and browser.

- Every page renders in the visitor's language, taken from the address when it carries one, and otherwise from their saved choice or `Accept-Language` header
- No flash of untranslated text: the HTML the server sends and the page after hydration are identical, catalog included
- Each request gets its own instance, so simultaneous visitors never see each other's language
- A one-call language switcher: `switchLocale` loads the catalog, then persists the choice for the next server render

SvelteKit needs the server package (`@verbaly/sveltekit`) alongside the Svelte package, the Vite plugin and the compiler:

```sh
npm install verbaly @verbaly/sveltekit @verbaly/svelte @verbaly/vite
# or: pnpm add verbaly @verbaly/sveltekit @verbaly/svelte @verbaly/vite
# or: yarn add verbaly @verbaly/sveltekit @verbaly/svelte @verbaly/vite
# or: bun add verbaly @verbaly/sveltekit @verbaly/svelte @verbaly/vite
```

```sh
npm install -D @verbaly/compiler
# or: pnpm add -D @verbaly/compiler
# or: yarn add -D @verbaly/compiler
# or: bun add -D @verbaly/compiler
```

```sh
npx verbaly init
```

`init` writes `verbaly.config.ts` and your source catalog. List your languages there (`locales: ['en', 'es']`): the build, `verbaly extract` and `verbaly check` all read them.

## Wire it up

Three wires on the server, one on the client. First the Vite plugin and the `lang` placeholder:

```html title="vite.config.ts · src/app.html"
// vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import verbaly from '@verbaly/vite';

export default { plugins: [verbaly(), sveltekit()] };

<!-- src/app.html -->
<html lang="%verbaly.lang%" dir="%verbaly.dir%">
```

The server hook resolves the language per request and fills the placeholder. Pass `routing` and the address decides when it carries the language, falling back to the saved choice, then `Accept-Language`, then your fallback:

```ts title="src/hooks.server.ts · src/app.d.ts"
// src/hooks.server.ts
import { verbalyHandle } from '@verbaly/sveltekit';
import { locales, routing } from 'verbaly/app';

export const handle = verbalyHandle({ locales, routing });

// src/app.d.ts
declare namespace App {
  interface Locals { verbalyLocale: string }
}
```

Hand the language to the client, then build **one instance per render** with the catalog awaited, the no-flash guarantee:

```svelte title="src/routes/+layout.server.ts · +layout.ts · +layout.svelte"
// +layout.server.ts
export const load = ({ locals }) => ({ locale: locals.verbalyLocale });

// +layout.ts
import { createRequestInstance } from 'verbaly/app';

export const load = async ({ data }) => ({
  ...data,
  verbaly: await createRequestInstance(data.locale),  // catalog ready BEFORE render
});

<!-- +layout.svelte -->
<script>
  import { provideVerbaly } from '@verbaly/svelte';
  let { data, children } = $props();
  provideVerbaly(data.verbaly);
</script>

{@render children()}
```

From here it's plain `@verbaly/svelte`: `useT()` / `useLocale()` stores and `Trans.svelte` work unchanged in every component.

`$t` is typed by your catalog: the types go to `src/verbaly.d.ts`, the folder SvelteKit's `tsconfig` reads, so `svelte-check` sees them with nothing to configure and fails on a key no catalog has.

> **Why hydration never flashes**
>
> The universal load runs on the server and again during hydration: same language from the hook, same catalog awaited before render. Both sides produce identical HTML, so nothing repaints and nothing mismatches.

## One route tree for every language

If your pages live at `/es/docs`, you do not need a route folder per language. One universal hook makes `/es/docs` render through your `/docs` route, so your routes stay exactly as they were:

```ts title="src/hooks.ts"
import { verbalyReroute } from '@verbaly/sveltekit';
import { locales } from 'verbaly/app';

export const reroute = verbalyReroute({ locales });
```

It goes in `hooks.ts` and not `hooks.server.ts`, because moving between pages in the browser has to resolve the same way the server did.

## Switching languages

`switchLocale` from `verbaly/app` already knows your languages and your URL mode. Hand it the instance this page renders with: with the language in the URL it goes to the same page in the other language, and without it it loads the catalog and switches the page in place. Either way it writes the cookie the server hook reads, so the next request already matches:

```svelte title="LangPicker.svelte"
<script>
  import { switchLocale } from 'verbaly/app';
  import { useVerbaly } from '@verbaly/svelte';

  // the instance this page renders with: one per request
  const verbaly = useVerbaly();
</script>

<button onclick={() => switchLocale('es', { instance: verbaly })}>Español</button>
```

- The cookie defaults to `verbaly-locale` (same identity as the core's storage key); `cookie: false` on either side disables it, for pure `Accept-Language`.
- `fallback` defaults to your first language; negotiation follows the order of preference of the browser, and `es-PE` matches `es`.
- No dependency on SvelteKit itself: the hook is typed structurally and stays compatible with SvelteKit 2 and 3.
