Tutorials
How to build a quiz in your players' language
Serve questions, tag names and your own interface text in any of the nine languages The Trivia API supports, with fuzzy tag search that copes with typos and missing accents. Built with Next.js.
Most people would rather play a quiz in their own language. The Trivia API has questions in nine languages, and the tag registry has tag names in the same nine. In this tutorial we build a quiz where the whole game is in the player's language, from the buttons to the questions.
The finished example is a Next.js app: play it here, or read the code on GitHub. It builds on the quiz by tag tutorial, so read that first if you haven't used the tag registry before.
The languages
The API supports these languages, by their ISO 639-1 codes:
| Code | Language |
|---|---|
en | English |
es | Spanish |
nl | Dutch |
hi | Hindi |
tr | Turkish |
fr | French |
de | German |
ru | Russian |
pt | Portuguese |
None of them are written right to left, so the layout never needs to flip. We keep the list in one place in the app, with each language's name in that language for the switcher:
export const LANGUAGES = ["en", "es", "nl", "hi", "tr", "fr", "de", "ru", "pt"] as const;
export type Language = (typeof LANGUAGES)[number];
export const isLanguage = (value: unknown): value is Language =>
typeof value === "string" && (LANGUAGES as readonly string[]).includes(value);Tags in the player's language
The tag registry takes a language parameter. You don't need a key for it:
curl "https://the-trivia-api.com/v2/tag-registry?language=es"Here are two of the tags it returns:
[
{
"slug": "food:french-cuisine",
"label": { "es": "Cocina francesa" },
"description": {
"es": "Platos, salsas, técnicas de cocina y comidas regionales de Francia."
},
"count": 21
},
{
"slug": "place:france",
"label": { "es": "Francia" },
"description": {
"es": "Preguntas sobre la historia, los lugares, la cultura y la gastronomía de Francia."
},
"count": 94
}
]You get only the language you asked for. Any other code gets a 400:
curl "https://the-trivia-api.com/v2/tag-registry?language=ja"Invalid language. Must be one of en, es, nl, hi, tr, fr, de, ru, pt (or not used at all). Instead received jaLoad the registry when you need it, in the player's language, and never copy it into your code or store it. Tags are added and counts change, and a stored copy quietly goes out of date. When the player switches language, load it again in the new one.
We fetch it on the server and flatten each tag to the strings we show, so the browser gets only what it needs. RegistryTag is the type from the quiz by tag tutorial:
export const fetchTags = async (language: Language) => {
const response = await fetch(
`https://the-trivia-api.com/v2/tag-registry?${new URLSearchParams({ language })}`
);
if (!response.ok) {
throw new Error(`The tag registry returned ${response.status}`);
}
const tags: RegistryTag[] = await response.json();
return tags
.map((tag) => ({
slug: tag.slug,
label: tag.label?.[language] ?? tag.label?.en ?? tag.slug,
description: tag.description?.[language] ?? tag.description?.en ?? "",
count: tag.count,
}))
.sort((a, b) => b.count - a.count);
};The slugs are the same in every language, so place:france is what you send to /v2/questions whether the player sees "Francia" or "Frankreich".
Questions in the player's language
/v2/questions takes language too. Translated questions need an API key with a Complete subscription, sent in the X-API-Key header:
curl "https://the-trivia-api.com/v2/questions?tags=place:france&types=text_choice&limit=1&language=es" \
-H "X-API-Key: YOUR_API_KEY"[
{
"category": "society_and_culture",
"id": "6af0114dc08d94fc732de3b6",
"correctAnswer": "Louis Vuitton",
"incorrectAnswers": ["Hermès", "Chanel", "Dior"],
"question": {
"text": "¿Qué casa francesa de lujo comenzó en 1854 como fabricante de baúles en París?"
},
"tags": [
"category:society-and-culture",
"category:history",
"org:fashion-houses",
"org:companies",
"topic:fashion",
"topic:business",
"era:19th-century",
"place:paris",
"place:france",
"place:europe",
"place:western-europe"
],
"type": "text_choice",
"difficulty": "medium",
"regions": [],
"isNiche": false
}
]The question and the answers are already in Spanish, so the quiz shows them as they are. The tags stay as slugs, the same as in the registry.
Without a key you get a 401, which means the request has to come from your server. Keep the key in an environment variable and never send it to the browser. In Next.js we do that in a server component, which runs only on the server:
export const fetchQuiz = async (tag: string, language: Language) => {
const params = new URLSearchParams({ limit: "10", types: "text_choice", tags: tag });
// English is the default, so we only send language for the other eight.
if (language !== "en") params.set("language", language);
const response = await fetch(`https://the-trivia-api.com/v2/questions?${params}`, {
headers: { "X-API-Key": process.env.TRIVIA_API_KEY ?? "" },
});
if (!response.ok) {
throw new Error(`The questions request returned ${response.status}`);
}
return response.json();
};We leave language out for English and let the API use its default.
Multiple choice only
We ask for types=text_choice, the multiple choice questions with one correct answer and three incorrect ones. That's the default, but we send it anyway to make the request clear. Each answer is a short string in the player's language, so all the quiz has to do is shuffle the four and compare the player's pick with correctAnswer.
Typed answers (text_input) are harder in another language. Players spell names differently and leave out accents, so you'd need to check answers with the answer validation endpoint as well. Multiple choice needs none of that.
The registry's count is for multiple choice questions too, so it matches what the quiz asks for. We show the count on every tag and disable the ones with a count of 0. A tag with fewer than 10 questions just gives a shorter round.
Picking the first language
We want the first page the player sees to be in their language, with no flash of English while the browser catches up. That means the server has to choose the language before it renders anything. It has two clues: a cookie, if the player has chosen a language before, and the Accept-Language header that every browser sends.
const parseAcceptLanguage = (header: string) =>
header
.split(",")
.map((part, index) => {
const [range, ...params] = part.trim().split(";");
const q = params.find((param) => param.trim().startsWith("q="));
const quality = q ? Number(q.trim().slice(2)) : 1;
return { code: range.split("-")[0].toLowerCase(), quality: Number.isNaN(quality) ? 0 : quality, index };
})
.filter((entry) => entry.code && entry.quality > 0)
.sort((a, b) => b.quality - a.quality || a.index - b.index)
.map((entry) => entry.code);
export const pickLanguage = (cookie: string | undefined, acceptLanguage: string | null): Language => {
if (isLanguage(cookie)) return cookie;
return parseAcceptLanguage(acceptLanguage ?? "").find(isLanguage) ?? "en";
};A cookie with a supported language wins. Otherwise we take the browser's most preferred language that the API supports, and if there isn't one we use English. Regional codes count as their language, so de-CH gives German:
pickLanguage(undefined, "de-CH,de;q=0.9,en;q=0.8"); // "de"
pickLanguage(undefined, "ja,ru;q=0.5"); // "ru"
pickLanguage(undefined, "ja"); // "en"
pickLanguage("pt", "de"); // "pt"In Next.js the layout reads both with cookies() and headers(), then sets <html lang> and loads the interface text for that language.
Remembering the choice
The language switcher stores the player's choice in two places: a cookie and localStorage.
The cookie is the one that matters. The browser sends it with every request, so the server knows the language before it renders the next page and the player never sees the wrong one. localStorage can't do that, because the server never sees it. We write the choice there as well so code in the browser can read it without asking the server, and we always treat the cookie as the source of truth.
The switcher calls a server action that sets the cookie. Setting a cookie in a server action makes Next.js render the page again, so everything switches language at once, including the tags and the questions:
"use server";
import { cookies } from "next/headers";
export async function setLanguage(language: string) {
if (!isLanguage(language)) return;
const cookieStore = await cookies();
cookieStore.set("quiz-language", language, {
path: "/",
maxAge: 60 * 60 * 24 * 365,
sameSite: "lax",
});
}const change = (next: string) => {
localStorage.setItem("quiz-language", next);
startTransition(() => setLanguage(next));
};The interface text
The questions and tags come from the API in the right language, but the buttons and headings are ours to translate. With about 40 strings we don't need an i18n library: one JSON file per language and a small t() function are enough.
{
"questionProgress": "Frage {current} von {total}",
"questionCount_one": "{count} Frage",
"questionCount_other": "{count} Fragen"
}Keys ending in _one or _other are plural forms, and Intl.PluralRules picks the right one for the number. Russian needs _few and _many as well ("3 вопроса", "5 вопросов"), and Intl.PluralRules knows that too:
export const createT = (language: Language, messages: Record<string, string>) => {
const plurals = new Intl.PluralRules(language);
const numbers = new Intl.NumberFormat(language);
return (key: string, values: Record<string, string | number> = {}) => {
let template = messages[key];
if (template === undefined && typeof values.count === "number") {
template = messages[`${key}_${plurals.select(values.count)}`] ?? messages[`${key}_other`];
}
if (template === undefined) return key;
return template.replace(/\{(\w+)\}/g, (match, name: string) => {
const value = values[name];
if (value === undefined) return match;
return typeof value === "number" ? numbers.format(value) : value;
});
};
};Intl.NumberFormat formats the counts the local way, so German shows "1.957 Fragen" where English shows "1,957 questions". The server sends the browser only the file for the current language.
Searching tags in any language
The search in the quiz by tag tutorial matches exact text. That's fine in English, but in other languages players often type without accents, and a French player looking for "Géographie" may well type geographie. We use Fuse.js for fuzzy matching, so typos still find the right tag, and fold accents away on both sides before comparing:
import Fuse from "fuse.js";
export const fold = (text: string) =>
text
.toLocaleLowerCase()
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
.replace(/ı/g, "i")
.replace(/ß/g, "ss")
.normalize("NFC");
export const createTagSearch = (tags: Tag[]) => {
const fuse = new Fuse(
tags.map((tag) => ({ ...tag, slugWords: tag.slug.replace(/[:-]/g, " ") })),
{
keys: [
{ name: "label", weight: 3 },
{ name: "slugWords", weight: 1.5 },
{ name: "description", weight: 1 },
],
threshold: 0.35,
ignoreLocation: true,
getFn: (tag, path) => fold(String(Fuse.config.getFn(tag, path) ?? "")),
}
);
return (query: string) => fuse.search(fold(query.trim())).map((result) => result.item);
};normalize("NFD") splits a letter like "é" into "e" and a separate accent, and the replace removes the accent. We only remove the Latin accents (U+0300 to U+036F), because Hindi vowel signs are combining marks too and the words need them. The two extra replacements cover the Turkish dotless "ı" and the German "ß", which don't split.
The getFn option folds the tag text, and we fold the query ourselves, so both sides match. With the French registry:
const search = createTagSearch(await fetchTags("fr"));
search("geographie").slice(0, 3).map((tag) => tag.label);
// ["Géographie", "Records géographiques", "Photographie"]
search("mamiferes").slice(0, 3).map((tag) => tag.label);
// ["Mammifères", "Rongeurs et petits mammifères", "Les Lumières"]mamiferes has a missing "m" as well as missing accents, and still finds "Mammifères" first. Searching the slug words means English names work in every language. With the Hindi registry, dinosaurs finds "डायनासोर" and chess finds "शतरंज".
Where to go next
- The example app's code has all of this wired up in Next.js, with the quiz screens and the interface text in all nine languages. Fork it and change whatever you like.
- The quiz by tag tutorial covers grouping tags by prefix and why one tag per quiz works best, and the API reference has every parameter for
/v2/tag-registryand/v2/questions.