Aller au contenu
Docs menuStrings / Use it in your app
On this page
  1. Same in every framework
  2. What init writes
  3. Locale routing
  4. Server
  5. Client
  6. Metadata
  7. Show a publish at once
  8. Serve the first request from a snapshot (optional)
  9. Typed keys
  10. Find broken texts

Use it in your app

Load your published strings in Next.js, TanStack Start, Vue, Svelte or plain JavaScript. Pick your framework once; the steps below follow it.

Your framework

You need a Lefine app with published strings and its app id (app_...). Find it in the app's Settings → General → App id, or let npx lefine init write it for you. The id never changes when you rename the app.

Same in every framework

Terminal
npm i lefinenpx lefine init

init signs you in, lets you pick the app (or pass --app <id or slug>), installs lefine and sets up your framework. It reads your package.json: Next.js, TanStack Start, or neither (Vue, Svelte, plain JS). Pick your framework above to see the files it writes and what to do next.

init writes · Next.jslefine.tsproxy.tsapp/[locale]/layout.tsxapp/[locale]/page.tsxapp/not-found.tsx

What init writes

init writes lefine.ts, proxy.ts, app/[locale]/layout.tsx and a first page in app/[locale]/page.tsx (plus app/not-found.tsx; it moves create-next-app's app/layout.tsx into the locale layout, see Server). lefine.ts looks like this:

lefine.ts
// lefine.tsimport { createLefine } from "lefine/next";export const lefine = createLefine({  project: "app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b",  locales: ["en", "de"],  defaultLocale: "en",});

prefix is "always" by default (every URL has a locale). Use "as-needed" to leave the default locale without one.

Locale routing

proxy.ts
// proxy.ts (middleware.ts before Next 16)import { lefine } from "./lefine";export default lefine.proxy;export const config = { matcher: ["/((?!api|_next|_vercel|.*\\..*).*)"] };

The locale comes from the URL, then the NEXT_LOCALE cookie, then Accept-Language, then defaultLocale.

Server

Your pages live under app/[locale]. Take the locale from params, so the page stays static.

app/[locale]/layout.tsx
// app/[locale]/layout.tsximport { notFound } from "next/navigation";import "../globals.css";import { lefine } from "@/lefine";/** Languages written right to left get dir="rtl". */const rtl = (locale: string) => /^(ar|ckb|dv|fa|he|ps|sd|ug|ur|yi)(-|$)/i.test(locale);export const generateStaticParams = () => lefine.locales.map((locale) => ({ locale }));export default async function Layout({ children, params }: { children: React.ReactNode; params: Promise<{ locale: string }> }) {  const { locale } = await params;  if (!lefine.locales.includes(locale)) notFound();  const t = await lefine.getStrings(locale, "home");  return (    <html lang={locale} dir={rtl(locale) ? "rtl" : "ltr"}>      <body>        <lefine.Provider locale={locale} namespaces={["nav"]}>          <h1>{t("title")}</h1>          {children}        </lefine.Provider>      </body>    </html>  );}

Only the namespaces you name in Provider reach the browser.

This is the root layout. init moves create-next-app's <html>, fonts, CSS and metadata from app/layout.tsx into this file, so lang and dir follow the locale (/he gets dir="rtl"). It then removes create-next-app's app/layout.tsx and app/page.tsx (the proxy sends / to a locale) and adds app/not-found.tsx for URLs outside every locale. There must be no app/layout.tsx above this one: then locale is a root param, and next dev with Partial Prefetching (on in create-next-app 16.4) does not print "Next.js encountered URL data". If your app/layout.tsx or app/page.tsx is your own, init keeps both and says what to move.

Client

tsx
"use client";import { useStrings } from "lefine/react";import { Link } from "lefine/next/link";export function Nav() {  const t = useStrings("nav");  return (    <>      <Link href="/pricing">{t("pricing")}</Link>      <Link locale="de">Deutsch</Link>    </>  );}

Link keeps the reader's locale. With locale and no href, it points to the current page in that language.

Metadata

app/[locale]/page.tsx
// app/[locale]/page.tsximport { lefine } from "@/lefine";export const generateMetadata = async ({ params }: { params: Promise<{ locale: string }> }) => ({  alternates: lefine.alternates((await params).locale, "/"),});

This gives the canonical URL and an hreflang link for every locale. The links are paths (/de). Set metadataBase in the layout's metadata (for example new URL("https://example.com")) so Next writes full URLs, which is what search engines expect.

Show a publish at once

Texts are cached for 60 seconds. To show a publish right away, add a webhook route and add its URL in Settings → Webhooks (Webhooks):

app/api/lefine/route.ts
// app/api/lefine/route.tsimport { lefine } from "@/lefine";export const POST = lefine.revalidate;

Set LEFINE_WEBHOOK_SECRET to the signing secret Lefine shows when you add the webhook.

Serve the first request from a snapshot (optional)

Your texts are not in your build: the first request after a deploy fetches them from the CDN, so it waits for two round trips. To serve that request at once, write a snapshot of the published texts while you build:

package.json
// package.json{  "scripts": {    "build": "lefine strings snapshot && next build"  }}
lefine.ts
// lefine.tsimport { createLefine } from "lefine/next";import snapshot from "./lefine-snapshot.json";export const lefine = createLefine({  project: "app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b",  locales: ["en", "de"],  defaultLocale: "en",  snapshot,});

lefine strings snapshot reads the app id from lefine.ts and writes lefine-snapshot.json. It needs no sign-in, because the CDN is public. Each language file is checked against the manifest, as at run time.

The trade-off: the snapshot is as old as your build. The first request after a deploy shows the texts from build time and asks the CDN in the background. From the next request, your pages show what is published now. If you publish between the build and the deploy, that first request shows the older text.

In our benchmark (200 keys, 3 languages, Next 16), the first request after a deploy took 61 ms with a snapshot and 127 ms without one. The other requests took about the same time either way. Without a snapshot nothing changes: leave it out if one slower first request is fine.

Typed keys

Terminal
npx lefine strings types -p app_…

This writes lefine-strings.d.ts with every key and its ICU arguments: {count, plural} needs a number, {d, date} a Date or a number, {name} a string or a number. Keep it in your tsconfig.json include. An unknown key or a missing argument is then a type error, in getStrings and in useStrings.

Find broken texts

In development, a text with a missing key, value or format gets a small red badge on the page. Its tooltip says what is wrong. Texts read only on the server (getStrings) print one console line instead. When you publish in Lefine while the app runs, a toast says how many strings of the page's language changed, with a Reload button. A production build has none of this code.

init writes · TanStack Startsrc/lefine.tssrc/routes/$locale/index.tsx

What init writes

init sees @tanstack/react-start in your package.json and writes two files: src/lefine.ts and a first page at src/routes/$locale/index.tsx.

Load on the server

src/lefine.ts
// src/lefine.tsimport { createServerFn } from "@tanstack/react-start";import { createStrings } from "lefine/server";export const locales = ["en", "de"];export const defaultLocale = "en";// Made inside the server function, so the browser bundle never gets the loader.let made: ReturnType<typeof createStrings> | undefined;export const strings = () => (made ??= createStrings({ project: "app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b" }));export const loadStrings = createServerFn({ method: "GET" })  .validator((locale: string) => (locales.includes(locale) ? locale : defaultLocale))  .handler(({ data }) => strings().load(data, ["home"]));

load(locale, namespaces) returns plain JSON: { locale, messages, timeZone }. Only the namespaces you name are sent.

Render

src/routes/$locale/index.tsx
// src/routes/$locale/index.tsximport { createFileRoute, notFound } from "@tanstack/react-router";import { StringsProvider, useStrings } from "lefine/react";import { loadStrings, locales } from "../../lefine";export const Route = createFileRoute("/$locale/")({  loader: ({ params }) => {    if (!locales.includes(params.locale)) throw notFound();    return loadStrings({ data: params.locale });  },  component: Page,});function Page() {  return (    <StringsProvider {...Route.useLoaderData()}>      <Home />    </StringsProvider>  );}function Home() {  const t = useStrings("home");  return <h1>{t("title")}</h1>;}

The loader runs on the server for the first page and as a server function call on client navigation. The ICU parser never reaches the browser.

Text outside components

For a <title> or other server-only text, use getStrings inside a server function:

ts
export const pageTitle = createServerFn({ method: "GET" })  .validator((locale: string) => locale)  .handler(async ({ data }) => (await strings().getStrings(data, "home"))("title"));

Texts as data, and the language menu

ts
const texts = await strings().texts("de", ["pricing"]); // { pricing: { cta: "Jetzt starten" } }, braces as writtenconst languages = await strings().languages(); // [{ code, name, nativeName, flagUrl, isSource }], source first

Call both inside a server function and pass the result down as props. There is no hook for them.

Routing and updates

Locale detection and links are yours: use TanStack Router's Link with the $locale param. The manifest is kept for 60 seconds, so a publish shows within a minute.

init writes · Vue, Svelte, plain JSsrc/lefine.ts

lefine has no Vue or Svelte package yet. You can still use it today: lefine/server loads and checks the texts, and lefine/strings formats them, ICU plurals included. Neither imports React.

What init writes

With no Next.js and no TanStack Start in package.json, init writes src/lefine.ts (the same file for Vue, Svelte or plain JS):

src/lefine.ts
// src/lefine.tsimport { createStrings } from "lefine/server";export const locales = ["en", "de"];export const defaultLocale = "en";export const strings = createStrings({ project: "app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b" });

lefine/server has no Node-only code, so it runs in the browser. The CDN allows requests from any site.

Vue 3

init does not write this one. Create src/i18n.ts yourself, next to the src/lefine.ts that init wrote:

src/i18n.ts
// src/i18n.tsimport { inject, type InjectionKey, type ShallowRef, shallowRef, type App } from "vue";import { createTranslator } from "lefine/strings";import type { StringsProps } from "lefine/server";import { strings } from "./lefine";const key: InjectionKey<ShallowRef<StringsProps>> = Symbol("lefine");const current = shallowRef<StringsProps>();/** Loads one language. Call it again to switch: every component updates. */export async function loadStrings(locale: string, namespaces: string[]) {  current.value = await strings.load(locale, namespaces);  document.documentElement.lang = locale;  document.documentElement.dir = /^(ar|ckb|dv|fa|he|ps|sd|ug|ur|yi)(-|$)/i.test(locale) ? "rtl" : "ltr";}export const lefinePlugin = { install: (app: App) => app.provide(key, current as ShallowRef<StringsProps>) };export function useStrings(namespace: string) {  const props = inject(key)!;  return (k: string, values?: Record<string, string | number | Date>) => createTranslator({ ...props.value, namespace })(k as never, values as never);}
src/main.ts
// src/main.tsimport { createApp } from "vue";import App from "./App.vue";import { defaultLocale, locales } from "./lefine";import { lefinePlugin, loadStrings } from "./i18n";const wanted = navigator.language.split("-")[0];await loadStrings(locales.includes(wanted) ? wanted : defaultLocale, ["home"]);createApp(App).use(lefinePlugin).mount("#app");
src/App.vue
<!-- src/App.vue --><script setup lang="ts">import { loadStrings, useStrings } from "./i18n";const t = useStrings("home");</script><template>  <h1>{{ t("title", { name: "Ada" }) }}</h1>  <button @click="loadStrings('de', ['home'])">Deutsch</button></template>

What works and what does not

Plurals, select, dates and numbers work as in React, because lefine/strings formats the ICU text. What you do not get yet: typed keys in templates, and server rendering with Nuxt (call strings.load in a server route and pass the result down by hand).

Plain JavaScript or Svelte

The same two calls work anywhere:

ts
import { createTranslator } from "lefine/strings";import { strings } from "./lefine";const props = await strings.load("de", ["home"]);const t = createTranslator({ ...props, namespace: "home" });t("title", { name: "Ada" });

In Svelte, keep props in a store and call strings.load again to switch language.

Why not vue-i18n with the CDN file?

You can fetch https://cdn.lefine.ai/app_.../en/translations.json (no version in the path: the newest published file) and pass it to vue-i18n. Simple texts and {name} work. Plurals do not: Lefine stores ICU ({count, plural, one {# item} other {# items}}) and vue-i18n uses its own one | many format, so a plural text shows as written.

Next step · ContentContent types
Was this page helpful?