awaitForTranslationOrThrow()
awaitForTranslationOrThrow is the translation method for scripts, build steps, and one-off
jobs — a static export, a pre-rendering pass, a migration. It looks up (and fetches, if
missing) the translated text for a target language, and rejects on a failed request, so a
run that cannot translate fails loudly instead of shipping source text.
Options are identical to
awaitForTranslationOrFallbackToOriginal
— see that page for context, namespace, unpersistedNamespace, replace,
forceTemporary, originLanguage, and debug.
Function Signature
awaitForTranslationOrThrow(
text: string,
language: Lang,
options?: {
context?: string;
namespace?: string;
unpersistedNamespace?: boolean;
replace?: Record<string, string>;
forceTemporary?: Partial<Record<Lang, string>>;
originLanguage?: Lang;
debug?: boolean;
}
): Promise<string>
awaitForTranslationOrThrow MUST be awaited to prevent 429 rate limit errors — and because an ignored rejection is what crashes the process on purpose. See Failure behaviour below.
Failure behaviour
On a failed request (network error, a not-ok API answer, or a custom handleTranslate
throw), the returned promise rejects with an Error whose message starts with:
i18n-keyless: FATAL: awaitForTranslationOrThrow failed for key "<key>"
The original error is attached as the error's cause.
An ignored rejection terminates the Node process — deliberately, so a script or build
step that cannot translate fails loudly instead of shipping the wrong text. A try/catch or
a .catch() is honoured: your handler runs, your process keeps going, and you own the
fallback.
Usage
A build script that pre-renders a set of pages, or a one-off migration:
import { awaitForTranslationOrThrow, type Lang } from 'i18n-keyless-node';
async function prerenderPages(pages: { slug: string; title: string }[], lang: Lang) {
const rendered = [];
for (const page of pages) {
// No try/catch: a failed translation is meant to stop the build.
const title = await awaitForTranslationOrThrow(page.title, lang);
rendered.push({ ...page, title });
}
return rendered;
}
try/catch is optional — only add it where you have a real fallback to fall back to; an
ignored rejection is the intended outcome otherwise:
try {
const title = await awaitForTranslationOrThrow(page.title, lang);
rendered.push({ ...page, title });
} catch (error) {
console.error(`Skipping page ${page.slug}:`, error);
}
Recommendation: enable the @typescript-eslint/no-floating-promises lint rule, so a
missing await is caught at lint time instead of at runtime.
Related
- awaitForTranslationOrFallbackToOriginal() - the non-throwing variant, for request handlers
- awaitForTranslation() (deprecated) - the old, single-behaviour alias
- I18nKeyless.init() - Initialize the library
- Types - Type definitions