Skip to Content
Guides

A site in several languages

How to put a Tifa site in several languages

You have a site and want each visitor to read it in their own language. By the end, every language has its own URLs, the interface text is translated, each page says its language in <html lang>, and search engines get the hreflang links that tie the versions of a page together.

A folder with a _locales folder is in several languages. That is the whole declaration: no list of languages in Go, no route constants, no language parameter in the folder names. The code below is from test/apps/i18n, and the storefront in examples/shop is a large working copy, with English as the default. For the reference of each setting see config.md and for the files Tifa generates, build.md.

Add the languages

Put a _locales folder in the folder that is in several languages, with one JSON file per language. A storefront in Chinese and English, with Chinese as the default:

app/
  store/
    _locales/
      zh-CN.json
      en-US.json
    page.tsx             /store and /en-US/store
    cart/page.tsx        /store/cart and /en-US/store/cart
    mine/route.go        /store/mine and /en-US/store/mine (an API route)
  projects/page.tsx      /projects only

A folder with a _locales folder is an area, and its languages are the names of its <language>.json files. Every page and API route in the area, and below it, is offered in those languages. A route outside every area has no language and one URL. Put _locales in app/ itself and the whole site is one area. An area below another one replaces the languages of the folder above for its own routes.

An API route in an area is served under every prefix too, such as /api/issues and /en-US/api/issues. That is on purpose: a handler answers in the language of the page that called it (c.Language()), and the functions Tifa generates call it with the current prefix. To serve an API at one URL only, keep it outside every area, in a folder with no _locales above it. When _locales is in app/ itself, every folder is in the area, so give the API folder an area of its own with a file for the default language only: app/api/_locales/zh-CN.json (with zh-CN as the default) makes app/api and everything below it answer at /api/... and nowhere else.

The same works for pages. A folder you do not translate, such as a staff area in a site that has two languages, gets an area of its own with one file, the default language's (app/staff/_locales/en-US.json holding {}). Its pages answer at one URL. The prefix of the default language redirects (308) to it, and the prefix of any other language is a 404.

A file name must be a language tag in its usual spelling: en-US, not en_US or en-us. Then name the default language and the address of the site in tifa.yaml:

i18n:
  default: zh-CN
site:
  url: https://shop.example.com

i18n.default may be left out when the site has one language. With several, it must be one of them, and every area must have a file for it. site.url is the scheme and host the site is served at, with no path. The hreflang links need it in full, and a guess from the request goes wrong behind a CDN. Both are settings of the project file only, like build.*.

The URLs

The default language has no prefix. Every other language is the first segment of the path:

URL Answer
/store/cart The page in zh-CN, the default
/en-US/store/cart The page in en-US
/zh-CN/store/cart 308 to /store/cart
/en-US/projects 404: /projects is outside every area, so it has no en-US
/fr/store/cart 404, because the store has no fr file

The query is kept on every redirect. A language-prefixed URL is the URL for everything after routing: the render memo, ETags, redirects and the copy a CDN keeps all work on the URL with the prefix, so the same path in two languages never shares an entry.

Set i18n.prefix: always to put the default language in the URL too. Then /store answers 308 to /zh-CN/store. Routes outside every area stay as they are.

i18n:
  default: zh-CN
  prefix: always

Two things the build refuses: a top-level folder of app/ named like a language of the site (app/en-US/ would be the first segment of that language's URLs), and a language in the htmlAttributes of documentHead or of a head, since Tifa writes <html lang> itself.

The language in code

In Go, c.Language() gives the language of the route being answered. It works in a Load, a Layout, a method handler and an API route:

// app/store/route.go
func Load(c *tifa.Ctx) (Data, error) {
	return Data{Language: c.Language(), Q: c.Query("q")}, nil
}

In React, useLanguage() from tifa/client gives the same:

import { useLanguage } from 'tifa/client'

const language = useLanguage() // "zh-CN" or "en-US"

Outside every area, on a site with languages, both give the default language. On a site without languages they give "". The functions Tifa generates for the handlers of an area call the URL with the current prefix, so c.Language() is the same in a handler as in the page that called it.

In a test, the Ctx from tifatest.NewCtx has the language of the request's path: httptest.NewRequest("GET", "/en-US/store/mine", nil) gives en-US, a path without a prefix the default language.

Translate the interface

The core has no translation library. Tifa ships an adapter for i18next and react-i18next, in tifa/i18n. Install both:

pnpm add i18next react-i18next

Tifa writes the adapter into .tifa/ when the site has languages and package.json lists react-i18next. The tsconfig.json from tifa new already maps tifa/*, which includes tifa/i18n.

Strings are nested JSON, one file per language:

{
  "title": "Store",
  "cart": { "title": "Cart", "items_one": "{{count}} item", "items_other": "{{count}} items" }
}

The namespace of an area is its folder relative to app/: app/store/_locales is store, app/admin/store/_locales is admin/store, and app/_locales is the default namespace. Wrap the pages in I18nProvider, once, in the root Layout:

// app/layout.tsx
import { Outlet } from '@tanstack/react-router'
import { I18nProvider } from 'tifa/i18n'

export default function Shell() {
  return (
    <I18nProvider>
      <Outlet />
    </I18nProvider>
  )
}

Then translate with the usual hook:

// app/store/cart/page.tsx
import { useTranslation } from 'tifa/i18n'

export default function Cart() {
  const { t } = useTranslation('store')
  return <h1>{t('cart.title')}</h1>
}

Outside a component, such as in the head of a route, translate with the instance: i18n.t('store:cart.title') with i18n from tifa/i18n. It is in the language of the page there too.

Every language is bundled with the app, so the server render and the browser have all the strings and nothing is fetched. Formatters such as money go at the top level of setup.ts at the app root, which runs before the first render on the server and in the browser (see setup.ts). A formatter gets the language as lng, so one serves every language:

// setup.ts
import { i18n } from 'tifa/i18n'

i18n.services.formatter?.addCached('currency', (lng, options) => {
  const f = new Intl.NumberFormat(lng, { currency: 'USD', ...options, style: 'currency' })
  return (value) => f.format(value)
})

Pass the language to Intl calls yourself, so the server and the browser print the same text (see Formatting so hydration matches). The server keeps the strings it translates, so a formatter must give the same text for the same language, options and value, as a React component must: put the time or anything of the request in the options of t, not in the formatter. More in The i18next adapter.

An area that has no strings in a language still needs its file: write {}. A key with no string shows the key itself. Tifa does not look in another language.

Validation messages

The message a Validate method returns in tifa.Fields reaches the visitor, so it needs their language. There are two ways, and one app can use both.

Translate in Go. Validate may take the Ctx, and c.Language() is the language of the URL the call was made to:

var nameMissing = map[string]string{"en-US": "Enter your name.", "zh-CN": "请输入姓名。"}

func (in SignUp) Validate(c *tifa.Ctx) error {
	fields := tifa.Fields{}
	if strings.TrimSpace(in.Name) == "" {
		fields["name"] = nameMissing[c.Language()]
	}
	return fields.Err()
}

The generated function of an area calls its handler with the current prefix, so the language in Validate is the language of the page. Keep a text for every language of tifa.Languages(), and let a test loop over that list, since a missing one gives an empty message. On a site without languages c.Language() is "".

Return codes and translate in the page. Validate returns a short code and the page turns it into text with the translation library it already uses:

fields["name"] = "name_missing"
const { t } = useTranslation('signup')
// fields comes from the TifaError of the call, see the forms guide
{fields.name && <span className="error">{t(`errors.${fields.name}`)}</span>}

with "errors": { "name_missing": "Enter your name." } in each _locales file.

Which one fits:

  • Codes fit when the page is the only caller and its texts already live in _locales. The translators work in one place, the library does plurals and formatting, and the same code can read differently in two places. The price: any other caller of the handler (an API client, a script) gets codes, and a code the page has no text for shows as the key.
  • Go texts fit when the handler has other callers, since the answer is a sentence in their language and needs no table. They also fit a message that holds facts only the server knows, such as "this name is taken" with the name in it, and an app that does not translate in the page at all. The price: the texts sit in Go, apart from the other strings of the interface.

Do not mix the two for one field, or the page cannot tell a code from a sentence.

Write links as if the site had one language:

<Link to="/store/cart">Cart</Link>

In the en-US document, Tifa makes it /en-US/store/cart and navigates in place. A link to a route outside the area, such as /projects, or a link that names another language loads a new page, because one document holds one language. The same goes for navigate, for a redirect from a Load, and for the links in the HTML of a content entry. You write nothing for it.

A redirect in Go follows the same rule: tifa.Redirect("/store/cart", 303) answering an en-US request goes to /en-US/store/cart. A path that starts with a language, such as /zh-CN/store/cart, goes where it says.

For a language switch, useAlternates() from tifa/client returns the URL of the page in each of its languages. Link to them with a plain <a>, since the other language is another document:

import { useAlternates, useLanguage } from 'tifa/client'

const names: Record<string, string> = { 'zh-CN': '中文', 'en-US': 'English' }

export function LanguageSwitch() {
  const versions = useAlternates()
  const current = useLanguage()
  return (
    <nav>
      {versions.map((v) => (
        <a key={v.language} href={v.url} aria-current={v.language === current ? 'page' : undefined}>
          {names[v.language]}
        </a>
      ))}
    </nav>
  )
}

The list is empty for a page with one version and for a page outside every area, so the switch shows nothing there.

The URLs have no query string: useAlternates() gives the same path for /store/products?page=2 and for /store/products, so a switch that links to them drops the filter and the page number. A switch keeps them when it adds the query of the address bar itself. Read it in an effect, since the server renders without a parameter its Load does not read and a read while rendering would not match (Query parameters in the server render). For example:

import { useEffect, useState } from 'react'
import { useRouter } from '@tanstack/react-router'

// The query of the address bar, such as "?q=shirt&page=2". It is empty on the server and in the
// first render of the browser, and follows every navigation of the router.
function useAddressQuery() {
  const router = useRouter()
  const [query, setQuery] = useState('')
  useEffect(() => {
    const read = () => setQuery(window.location.search)
    read()
    return router.subscribe('onResolved', read)
  }, [router])
  return query
}

Then const query = useAddressQuery() and <a href={v.url + query}> in the switch above keep the query. The other page shows only the parameters its own Load reads, so it filters the same way when both languages read the same names.

What search engines get

On a page that has more than one version, Tifa adds to the head:

  • a <link rel="alternate" hreflang="..."> for every version, the page itself included
  • hreflang="x-default", pointing at the default language's version

Every page, with one version or more, also gets a <link rel="canonical"> for itself, and an og:url meta with the same URL (see Search engines). The URLs are in full, from site.url. The versions have no query. The canonical URL keeps the query parameters the Load and Layouts of the page read, as the server renders it (see Query parameters), so page 2 of a list is its own page. A canonical you write in your own head wins over the one from Tifa. There are no links on a 404 or an error page, and no hreflang links on a page with one version.

/sitemap.xml lists each page once per language with the same hreflang links (see Search engines and language models).

By default a page exists in every language of its area at the same path under another prefix, parameter pages included. That is wrong when a page has another slug in another language, or exists in only one. Say so in its Load with c.SetAlternates. Write each path as the visitor sees it, escaped, without the prefix and the query, and include the page itself:

// app/store/journal/slug+/route.go
func Load(c *tifa.Ctx) (Data, error) {
	slug := c.Param("slug")
	translations, ok := entries[slug] // e.g. {zh-CN, ni-hao}, {en-US, hello}
	if !ok {
		return Data{}, tifa.ErrNotFound
	}
	var versions []tifa.Alternate
	for _, t := range translations {
		versions = append(versions, tifa.Alternate{Language: t.Language, Path: "/store/journal/" + t.Slug})
	}
	c.SetAlternates(versions)
	return Data{Slug: slug}, nil
}

The hreflang links and useAlternates() both follow this list, so the switch links /store/journal/ni-hao to /en-US/store/journal/hello. A language left out of the list has no version of this page. An empty list says the page has one version. The page fails with an error in the log when a language is not one of the page's languages, is listed twice, or has a path that is not a plain escaped path. Give the sitemap the same list in the Alternates of the page, so it agrees with the head (see Several languages).

Posts in each language

A content collection with Languages: tifa.Languages() has a folder per language under content/:

// content.go
var Journal = content.Define[Entry](content.Source{Dir: "journal", Languages: tifa.Languages()})
content/journal/
  zh-CN/hello.md
  en-US/hello.md

tifa.Languages() is the languages of the site, the default first. It gives the same list under tifa build, tifa dev, go test and go run. Read the entries with c.Language():

e, err := Journal.Get(c.Language(), "hello")

An entry missing in a language has no page in it: Get returns tifa.ErrNotFound, the page is a 404, and there is no fallback to another language. A translation that is scheduled by its date appears by itself at that date. entry.Translations lists the versions that can be seen now, which is what a page of an entry passes to SetAlternates. See Content for the rest.

In the Markdown, write links as root-relative paths, such as [cart](/store/cart). The build adds the prefix of the entry's language when the page has that language: /en-US/store/cart in the en-US entry. A link that already starts with a language stays as written.

Moving from a lang+ folder

An app that keeps the language in a lang+ folder, with no _locales folder, works as it did. To move it over:

  1. Move the pages and the route.go out of the lang+ folder into its parent, and write the strings as _locales/<language>.json there.
  2. Delete the Layout that checked the language, the lang in its head and the hand-written hreflang links. Tifa writes them.
  3. Read the language with c.Language() and useLanguage() where the code read params.lang.
  4. Delete the redirect from /store by Accept-Language or cookie unless you still want it: /store is now the page in the default language.

While you work

  • tifa dev picks up a new _locales/fr.json without a restart. /fr/store works at once. Removing the file makes it 404.
  • A fr.draft.json is not published. The language does not exist for the site until the file is renamed to fr.json. Use it for a translation in progress.
  • Plain go test works with tifa.Languages(). It reads the _locales folders and tifa.yaml of the module.

What fails the build

tifa build and tifa check stop with the file and the reason for:

  • an area without a file for the default language
  • several languages and no i18n.default, or one that no area has
  • several languages and no site.url
  • a file name that is not a language tag in its usual spelling
  • a _locales folder with no language file
  • a top-level folder of app/ named like a language of the site
  • a lang in htmlAttributes on a site with languages
  • a Languages: of a content collection that is neither tifa.Languages() nor a list of string literals

What Tifa does not do

  • It does not choose a language for a visitor. There is no redirect by Accept-Language, a cookie or the address. The URL is the choice, so every URL is the same page for everyone, a search engine can find it, and a CDN can keep it (see Cache for CDNs). If your site wants to send a first-time visitor to their language, write a handler for it on a route outside every area, with Cache off.
  • It does not remember the choice. If you want to, set a cookie in the app when the visitor picks a language, and read it in the handler above.
  • It has no fallback language. A missing string shows its key, a missing entry is a 404, and a language an area has no file for is a 404.