lokalise-pack
Complete Lokalise integration skill pack with 24 skills covering translation management, localization workflows, and i18n automation. Flagship tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install lokalise-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> Claude Code skill pack for Lokalise translation management — 24 skills covering the full localization lifecycle from SDK setup through production operations.
Skills (24)
'Configure Lokalise CI/CD integration with GitHub Actions and automated.
Lokalise CI Integration
Overview
Automate the full translation lifecycle through GitHub Actions: upload source strings when code is pushed, download translations during builds, block PRs with missing translations, and manage branch-based translation workflows that mirror your Git branching strategy. The goal is zero manual translation file management — developers write code, translators work in Lokalise, and CI keeps everything in sync.
Prerequisites
- Lokalise project with Project ID (Settings > General > Project ID)
- Lokalise API token with read/write permissions (Profile > API Tokens), stored as
LOKALISEAPITOKENGitHub secret LOKALISEPROJECTIDstored as GitHub secret (or variable)- Lokalise CLI v2 (
lokalise2) — installed in CI viacurl -sfL https://raw.githubusercontent.com/nicktomlin/lokalise-cli-2-install/master/install.sh | sh - Source locale files committed to the repository (e.g.,
src/locales/en.json)
Instructions
Step 1: Upload Source Strings on Push
Create .github/workflows/lokalise-upload.yml to push source strings to Lokalise whenever the default locale file changes on main:
name: Upload translations to Lokalise
on:
push:
branches: [main]
paths:
- 'src/locales/en.json' # Adjust to your source locale path
jobs:
upload:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Lokalise CLI
run: |
curl -sfL https://raw.githubusercontent.com/lokalise/lokalise-cli-2-go/master/install.sh | sh
sudo mv ./bin/lokalise2 /usr/local/bin/lokalise2
- name: Upload source strings
run: |
lokalise2 file upload \
--token "${{ secrets.LOKALISE_API_TOKEN }}" \
--project-id "${{ secrets.LOKALISE_PROJECT_ID }}" \
--file "src/locales/en.json" \
--lang-iso "en" \
--replace-modified \
--include-path \
--distinguish-by-file \
--poll \
--poll-timeout 120s
# --replace-modified updates existing keys with new values
# --poll waits for the async upload to complete before exiting
Step 2: Download Translations During Build
Create .github/workflows/lokalise-build.yml or add a step to your existing build workflow:
name: Build with translations
on:
push:
branches: [main, staging]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Lokalise CLI
run: |
curl -sfL https://raw.githubusercontent.com/lokalise/lokalise-cli-2-go/master/install.sh | sh
sudo mv ./b'Diagnose and fix Lokalise common errors and exceptions.
Lokalise Common Errors
Overview
Every Lokalise API error returns a JSON body with a consistent structure. This skill covers the error response format, diagnosis of each HTTP status code (401, 400, 404, 429, 413, 500, 503), diagnostic curl commands for rapid troubleshooting, and a reusable error handling wrapper for the Node SDK.
Prerequisites
curlavailable for diagnostic commands@lokalise/node-apiSDK installed for the error wrapper- API token stored in
LOKALISEAPITOKENenvironment variable jqinstalled for parsing JSON responses (optional but recommended)
Instructions
1. Understand the Error Response Format
All Lokalise API errors return this structure:
{
"error": {
"message": "Human-readable error description",
"code": 401
}
}
The code field mirrors the HTTP status code. The message field provides specifics. When using the Node SDK, errors are thrown as exceptions with error.code, error.message, and error.headers properties.
2. Diagnose by Status Code
401 Unauthorized — Invalid or Missing API Token
{"error": {"message": "Invalid `X-Api-Token` header", "code": 401}}
Causes:
- Token is incorrect, expired, or revoked
X-Api-Tokenheader missing from request- Token copied with leading/trailing whitespace
Fix:
# Verify your token works
curl -s -o /dev/null -w "%{http_code}" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}" \
"https://api.lokalise.com/api2/teams"
# Expected: 200
# If 401: regenerate token at https://app.lokalise.com/profile#apitokens
# Check for whitespace in token
echo -n "$LOKALISE_API_TOKEN" | xxd | head -2
# Look for 0a (newline) or 20 (space) at start/end
400 Bad Request — Validation Errors
{"error": {"message": "Invalid parameter `platform` - must be one of: ios, android, web, other", "code": 400}}
Common 400 causes:
- Invalid
project_idformat (must be{number}.{alphanumeric}) - Missing required fields in POST/PUT body
- Invalid language ISO code
- Key name exceeding 256 characters
- Invalid platform value (must be
ios,android,web, orother)
Fix:
# Validate project ID format
curl -s -H "X-Ap'Execute Lokalise primary workflow: Upload source files and manage translation.
Lokalise Core Workflow A
Overview
Primary workflow covering the "source to Lokalise" direction: upload translation files, create and update keys programmatically, tag keys for organization, and perform bulk operations. Both SDK and CLI approaches shown for every operation.
Prerequisites
- Lokalise API token exported as
LOKALISEAPITOKEN - Lokalise project ID exported as
LOKALISEPROJECTID @lokalise/node-apiinstalled for SDK exampleslokalise2CLI installed for CLI examples- Source translation file(s) in a supported format (JSON, XLIFF, PO, YAML, etc.)
Instructions
- Upload source translation files. File upload is async: the API returns a process object that must be polled until completion.
SDK — Base64 encode and upload:
import { LokaliseApi } from "@lokalise/node-api";
import { readFileSync } from "node:fs";
const client = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
const PROJECT_ID = process.env.LOKALISE_PROJECT_ID!;
// Read and base64-encode the source file
const fileContent = readFileSync("./locales/en.json");
const base64Data = fileContent.toString("base64");
const uploadProcess = await client.files().upload(PROJECT_ID, {
data: base64Data,
filename: "en.json",
lang_iso: "en",
replace_modified: true, // Overwrite changed translations
distinguish_by_file: true, // Same key names in different files stay separate
tags: ["source", "v2.1"], // Auto-tag uploaded keys
});
console.log(`Upload queued: process ${uploadProcess.process_id}, status: ${uploadProcess.status}`);
SDK — Poll upload process until complete:
async function waitForUpload(
client: LokaliseApi,
projectId: string,
processId: string,
maxWaitMs = 60_000
): Promise<void> {
const start = Date.now();
while (Date.now() - start < maxWaitMs) {
const proc = await client.queuedProcesses().get(processId, { project_id: projectId });
console.log(` Process ${processId}: ${proc.status}`);
if (proc.status === "finished") return;
if (proc.status === "cancelled" || proc.status === "failed") {
throw new Error(`Upload ${proc.status}: ${JSON.stringify(proc.details)}`);
}
await new Promise((r) => setTimeout(r, 1000));
}
throw new Error(`Upload timed out after ${maxWaitMs}ms`);
}
await waitForUpload(client, PROJECT_ID, uploadProcess.process_id);
console.log("Upload complete");
CLI — Upload with polling:
set -euo pipefail
lokalise2 --token "$LOKALISE_API_TOKEN" file upload \
--project-id "$LOKALISE_PROJ'Manage Lokalise secondary workflow: Download translations and integrate.
Lokalise Core Workflow B
Overview
Everything on the "Lokalise to app" side: download translated files, manage translations and review status, leverage translation memory, manage contributors and their language access, and handle format differences across JSON, XLIFF, and PO files.
Prerequisites
- Lokalise API token exported as
LOKALISEAPITOKEN - Lokalise project ID exported as
LOKALISEPROJECTID @lokalise/node-apiinstalled for SDK exampleslokalise2CLI installed for CLI examplesunzipavailable for extracting download bundles
Instructions
- Download translated files. The download endpoint returns an S3 URL to a zip bundle — request the bundle, download the zip, then extract.
SDK — Download and extract:
import { LokaliseApi } from "@lokalise/node-api";
import { execSync } from "node:child_process";
import { mkdirSync } from "node:fs";
const client = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
const PROJECT_ID = process.env.LOKALISE_PROJECT_ID!;
// Request the download bundle
const download = await client.files().download(PROJECT_ID, {
format: "json",
original_filenames: false,
bundle_structure: "%LANG_ISO%.json", // Output: en.json, fr.json, de.json
filter_langs: ["en", "fr", "de", "es"], // Only these languages
export_empty_as: "base", // Use base language for empty translations
include_tags: ["release-3.0"], // Only keys with this tag
replace_breaks: false,
});
const bundleUrl = download.bundle_url;
console.log(`Bundle URL: ${bundleUrl}`);
// Download and extract
mkdirSync("./locales", { recursive: true });
execSync(`curl -sL "${bundleUrl}" -o /tmp/lokalise-bundle.zip`);
execSync(`unzip -o /tmp/lokalise-bundle.zip -d ./locales`);
console.log("Translations extracted to ./locales/");
CLI — Download with structure:
set -euo pipefail
lokalise2 --token "$LOKALISE_API_TOKEN" file download \
--project-id "$LOKALISE_PROJECT_ID" \
--format json \
--original-filenames=false \
--bundle-structure "locales/%LANG_ISO%.json" \
--filter-langs "en,fr,de,es" \
--export-empty-as base \
--replace-breaks=false \
--unzip-to .
SDK — Download with original file structure preserved:
const download = await client.files().download(PROJECT_ID, {
format: "json",
original_filenames: true,
directory_prefix: "", // No extra prefix
export_empty_as: "skip", // 'Optimize Lokalise costs through plan selection, usage monitoring, and.
Lokalise Cost Tuning
Overview
Optimize Lokalise localization spending across plan tiers, contributor seats, Translation Memory (TM) leverage, machine translation (MT) triage, and dead key cleanup. Lokalise pricing is per-seat subscription (Essential ~$120/user/month, Pro ~$290/user/month) with optional pay-per-use for MT and AI features.
Prerequisites
- Lokalise Admin role for billing and usage visibility
LOKALISEAPITOKENwith read access to project statistics- Understanding of translation workflow (human, MT, or hybrid)
curlandjqfor API queries
Instructions
Step 1: Audit Current Usage
set -euo pipefail
echo "=== Lokalise Usage Audit ==="
# Get all projects with statistics
PROJECTS=$(curl -sf "https://api.lokalise.com/api2/projects?limit=100&include_statistics=1" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}")
echo "$PROJECTS" | jq -r '.projects[] | [.name, .statistics.keys_total, (.statistics.languages // [] | length), .statistics.progress_total] | @tsv' \
| column -t -s $'\t' -N "Project,Keys,Languages,Progress%"
# Totals
TOTAL_KEYS=$(echo "$PROJECTS" | jq '[.projects[].statistics.keys_total] | add')
TOTAL_LANGS=$(echo "$PROJECTS" | jq '[.projects[] | (.statistics.languages // [] | length)] | max')
PROJECT_COUNT=$(echo "$PROJECTS" | jq '.projects | length')
echo ""
echo "Totals: ${PROJECT_COUNT} projects, ${TOTAL_KEYS} keys, up to ${TOTAL_LANGS} languages"
echo ""
# Contributor count (seats = cost driver)
TEAMS=$(curl -sf "https://api.lokalise.com/api2/teams" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}")
echo "$TEAMS" | jq -r '.teams[] | "Team: \(.name) — \(.users_count) users (seats)"'
Step 2: Reduce Per-Seat Costs
Seats are the largest cost driver. Strategies to minimize:
import { LokaliseApi } from "@lokalise/node-api";
const lok = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
// Audit: Find inactive contributors (no activity in 90 days)
async function findInactiveContributors(projectId: string): Promise<void> {
const contributors = await lok.contributors().list({
project_id: projectId,
limit: 500,
});
console.log("=== Contributor Activity Audit ===");
for (const c of contributors.items) {
const langs = c.languages
.map((l: { lang_iso: string }) => l.lang_iso)
.join(", ");
console.log(
`${c.fullname} <${c.email}> — ` +
`admin: ${c.is_admin}, reviewer: ${c.is_reviewer}, ` +
`languages: [${langs}]`
);
}
console.log(`\nTotal contributors: ${contributors.items.length}`);
console.log'Implement Lokalise translation data handling, PII management, and compliance.
Lokalise Data Handling
Overview
Lokalise manages translation data through keys, translations, snapshots, and branches. This skill covers the translation data lifecycle (create, update, export), key metadata management (tags, descriptions, screenshots), translation snapshots for versioning, branch-based translation isolation, export format handling (JSON flat/nested, XLIFF, PO), character encoding (UTF-8 BOM handling), and plural form support across locales.
Prerequisites
@lokalise/node-apiSDK installed (npm install @lokalise/node-api)- API token with read/write access to the target project
- Understanding of i18n key naming conventions for your project
lokalise2CLI for bulk file operations (optional)
Instructions
1. Understand the Translation Data Lifecycle
Translation data in Lokalise follows this flow: Create keys (with platforms, tags, descriptions) -> Add base translations (source language) -> Translate (manually or via integrations) -> Review (proofread flag) -> Export (download to codebase).
Create keys with metadata that helps translators:
import { LokaliseApi } from "@lokalise/node-api";
const lokalise = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
// Create keys with rich metadata
await lokalise.keys().create({
project_id: projectId,
keys: [
{
key_name: {
ios: "welcome.title",
android: "welcome_title",
web: "welcome.title",
other: "welcome.title",
},
description: "Main heading on the welcome screen shown after signup",
platforms: ["web", "ios", "android"],
tags: ["onboarding", "v2.1"],
base_translations: [
{ language_iso: "en", translation: "Welcome to {{appName}}" },
],
is_plural: false,
is_hidden: false,
},
],
});
2. Manage Key Metadata
Tags, descriptions, and screenshots help translators understand context. Keep metadata current:
// Bulk update tags for release management
await lokalise.keys().bulk_update({
project_id: projectId,
keys: [
{ key_id: 12345, tags: ["release-3.0", "reviewed"] },
{ key_id: 12346, tags: ["release-3.0", "needs-review"] },
],
});
// Add a screenshot for visual context
await lokalise.screenshots().create({
project_id: projectId,
screenshots: [
{
data: base64EncodedImage, // Base64 JPEG/PNG, max 6 MB
title: "Welcome screen — mobile layout",
description: "Shows welcome.title and welcome.subtitle keys",
key_ids: [12345, 12346],
'Collect Lokalise debug evidence for support tickets and troubleshooting.
Lokalise Debug Bundle
Current State
!node --version 2>/dev/null || echo 'N/A'
!python3 --version 2>/dev/null || echo 'N/A'
!uname -a
Overview
Collect all diagnostic information needed to troubleshoot Lokalise integration issues or file a support ticket — environment versions, SDK/CLI status, API connectivity, project listings with key counts, upload process status, and redacted logs, bundled into a timestamped .tar.gz archive.
Prerequisites
LOKALISEAPITOKENenvironment variable set (or token available to provide)curlandjqavailable on PATH- Optional:
@lokalise/node-apiSDK installed in current project - Optional:
lokalise2CLI installed
Instructions
Step 1: Create the Bundle Directory
set -euo pipefail
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BUNDLE_DIR="lokalise-debug-${TIMESTAMP}"
mkdir -p "${BUNDLE_DIR}"
echo "Bundle directory: ${BUNDLE_DIR}"
Step 2: Collect Environment Information
set -euo pipefail
cat > "${BUNDLE_DIR}/environment.txt" <<ENVEOF
=== System ===
OS: $(uname -srm)
Shell: ${SHELL:-unknown}
Date: $(date -u +"%Y-%m-%dT%H:%M:%SZ")
=== Runtime Versions ===
Node.js: $(node --version 2>/dev/null || echo 'not installed')
npm: $(npm --version 2>/dev/null || echo 'not installed')
Python: $(python3 --version 2>/dev/null || echo 'not installed')
=== Lokalise SDK ===
$(npm list @lokalise/node-api 2>/dev/null || echo 'SDK not found in project')
=== Lokalise CLI ===
$(lokalise2 --version 2>/dev/null || echo 'CLI not installed')
=== Token Status ===
LOKALISE_API_TOKEN: $([ -n "${LOKALISE_API_TOKEN:-}" ] && echo "SET (${#LOKALISE_API_TOKEN} chars)" || echo "NOT SET")
ENVEOF
echo "Environment info collected."
Step 3: Test API Connectivity
set -euo pipefail
echo "=== API Connectivity Test ===" > "${BUNDLE_DIR}/api-connectivity.txt"
# Test DNS resolution
echo -e "\n--- DNS Resolution ---" >> "${BUNDLE_DIR}/api-connectivity.txt"
nslookup api.lokalise.com 2>&1 | tail -4 >> "${BUNDLE_DIR}/api-connectivity.txt" || echo "nslookup failed" >> "${BUNDLE_DIR}/api-connectivity.txt"
# Test HTTPS connectivity and response time
echo -e "\n--- HTTPS Connectivity ---" >> "${BUNDLE_DIR}/api-connectivity.txt"
curl -s -o /dev/null -w "HTTP Status: %{http_code}\nConnect Time: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal Time: %{time_total}s\nRemote IP: %{remote_ip}\n" \
-H "X-Api-Tok'Deploy Lokalise integrations to Vercel, Netlify, and Cloud Run platforms.
Lokalise Deploy Integration
Overview
Translations must be downloaded fresh during CI/CD builds to ensure production always ships the latest reviewed content. This skill covers downloading translations as a build step, GitHub Actions workflows for translation sync, Vercel and Netlify build plugin integration, OTA (over-the-air) updates for mobile apps via Lokalise's iOS and Android SDKs, and environment-specific translation bundles.
Prerequisites
- Lokalise API token with download permissions (read-only token recommended for CI)
LOKALISEAPITOKENandLOKALISEPROJECTIDstored as CI secretscurlandunzipavailable in CI environment (standard on GitHub Actions runners)- For OTA: Lokalise OTA SDK token (separate from API token, generated in Lokalise dashboard)
Instructions
1. Download Translations in the Build Step
Add a pre-build script that pulls translations from Lokalise before your framework compiles:
#!/bin/bash
# scripts/download-translations.sh
set -euo pipefail
PROJECT_ID="${LOKALISE_PROJECT_ID:?Missing LOKALISE_PROJECT_ID}"
API_TOKEN="${LOKALISE_API_TOKEN:?Missing LOKALISE_API_TOKEN}"
DEST_DIR="${1:-./src/locales}"
echo "Downloading translations for project $PROJECT_ID..."
BUNDLE_URL=$(curl -sf -X POST \
"https://api.lokalise.com/api2/projects/${PROJECT_ID}/files/download" \
-H "X-Api-Token: ${API_TOKEN}" \
-H "Content-Type: application/json" \
-d "{
\"format\": \"json\",
\"original_filenames\": false,
\"bundle_structure\": \"%LANG_ISO%.json\",
\"export_empty_as\": \"base\",
\"json_unescaped_slashes\": true,
\"include_tags\": [\"production\"],
\"filter_data\": [\"translated\", \"reviewed\"]
}" | jq -r '.bundle_url')
if [ -z "$BUNDLE_URL" ] || [ "$BUNDLE_URL" = "null" ]; then
echo "ERROR: Failed to get bundle URL from Lokalise"
exit 1
fi
mkdir -p "$DEST_DIR"
curl -sfL "$BUNDLE_URL" -o /tmp/translations.zip
unzip -o /tmp/translations.zip -d "$DEST_DIR"
rm /tmp/translations.zip
FILE_COUNT=$(ls -1 "$DEST_DIR"/*.json 2>/dev/null | wc -l)
echo "Downloaded $FILE_COUNT translation files to $DEST_DIR"
Wire it into package.json:
{
"scripts": {
"prebuild": "./scripts/download-translations.sh ./src/locales",
"build": "next build"
}
}
2. GitHub Actions Workflow
Full workflow that downloads translations, builds, and deploys:
'Configure Lokalise enterprise SSO, role-based access control, and team.
Lokalise Enterprise RBAC
Overview
Manage fine-grained access to Lokalise translation projects using its built-in role hierarchy, language-level scoping, contributor groups, and organization-level SSO enforcement. Lokalise has four core roles — owner, admin, manager-level (via admin_rights), and contributor (translator/reviewer) — each configurable per project and per language.
Prerequisites
- Lokalise Team or Enterprise plan (contributor groups and SSO require Team+)
- Owner or Admin role in the Lokalise organization
LOKALISEAPITOKENenvironment variable set (admin-level token)@lokalise/node-apiSDK orcurl+jqfor REST API access
Instructions
Step 1: Understand the Role Hierarchy
Lokalise uses a flat role model per project, controlled by three boolean flags on each contributor:
| Role | is_admin |
is_reviewer |
Can translate | Can review | Can manage keys | Can manage contributors |
|---|---|---|---|---|---|---|
| Admin | true |
true |
Yes | Yes | Yes | Yes |
| Manager | false |
true |
Yes | Yes | Limited (via admin_rights) |
No |
| Reviewer | false |
true |
Yes | Yes | No | No |
| Translator | false |
false |
Yes | No | No | No |
At the team level, users are either admin or member. Team admins can create projects and manage billing. Team members can only access projects they are explicitly added to.
Step 2: Add Contributors with Language Scoping
import { LokaliseApi } from '@lokalise/node-api';
const lok = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
// Add a translator restricted to French and Spanish only
await lok.contributors().create(PROJECT_ID, [{
email: 'translator@agency.com',
fullname: 'Marie Dupont',
is_admin: false,
is_reviewer: false,
languages: [
{ lang_iso: 'fr', is_writable: true },
{ lang_iso: 'es', is_writable: true },
],
}]);
// Add a reviewer who can review all languages but only translate German
await lok.contributors().create(PROJECT_ID, [{
email: 'reviewer@company.com',
fullname: 'Hans Mueller',
is_admin: false,
is_reviewer: true,
languages: [
{ lang_iso: 'de', is_writable: true },
{ lang_iso: 'fr', is_writable: false }, // Can review'Create a minimal working Lokalise example.
Lokalise Hello World
Overview
End-to-end walkthrough: list projects, create a test project, add keys, set translations across languages, and retrieve them. Covers both the Node SDK (@lokalise/node-api) and the CLI (lokalise2).
Prerequisites
- Lokalise API token exported as
LOKALISEAPITOKEN - Node.js 18+ with
@lokalise/node-apiinstalled (npm i @lokalise/node-api) - Lokalise CLI v2 installed (
brew install lokalise2or binary releases)
Instructions
- List all projects using the SDK and CLI.
import { LokaliseApi } from "@lokalise/node-api";
const client = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
const projects = await client.projects().list({ page: 1, limit: 20 });
for (const p of projects.items) {
console.log(`${p.project_id} ${p.name} (${p.statistics.languages} languages)`);
}
set -euo pipefail
lokalise2 --token "$LOKALISE_API_TOKEN" project list
- Create a test project with three languages.
const project = await client.projects().create({
name: "hello-world-test",
description: "Quick start demo",
languages: [
{ lang_iso: "en", custom_name: "English" },
{ lang_iso: "fr", custom_name: "French" },
{ lang_iso: "de", custom_name: "German" },
],
base_language_iso: "en",
});
const PROJECT_ID = project.project_id;
console.log(`Created project: ${PROJECT_ID}`);
- Add translation keys with their English (base language) translations in a single call.
const keys = await client.keys().create({
project_id: PROJECT_ID,
keys: [
{
key_name: { web: "greeting.hello" },
platforms: ["web"],
translations: [{ language_iso: "en", translation: "Hello" }],
},
{
key_name: { web: "greeting.goodbye" },
platforms: ["web"],
translations: [{ language_iso: "en", translation: "Goodbye" }],
},
{
key_name: { web: "app.title" },
platforms: ["web"],
translations: [{ language_iso: "en", translation: "My Application" }],
},
],
});
console.log(`Created ${keys.items.length} keys`);
- Set translations for French and German by retrieving key IDs and updating each translation.
const allKeys = await client.keys().list({
project_id: PROJECT_ID,
limit: 100,
});
const translations: Record<string, Record<stri'Execute Lokalise incident response procedures with triage, mitigation,.
Lokalise Incident Runbook
Overview
Rapid-response procedures for Lokalise-related incidents in production. Covers quick diagnostics (API health, token validity, rate limit status), triage for five common failure modes (missing translations, stale translations, API outage, file upload failures, OTA failures), fallback to cached translations, and communication templates for stakeholder notification. Designed to be executed under pressure — each section is self-contained.
Prerequisites
curlandjqavailable on the responder's machine- Production Lokalise API token accessible (from secret manager or break-glass procedure)
LOKALISEPROJECTIDknown (check your deployment config or Lokalise dashboard)- Access to application logs (Datadog, CloudWatch, GCP Logging, or equivalent)
- Incident communication channel (Slack, PagerDuty, or equivalent)
Instructions
Step 1: Quick Diagnostics (Run First)
Execute these three checks immediately to narrow the problem scope. Copy-paste into your terminal:
#!/bin/bash
# incident-diagnostics.sh — Run all three checks in sequence
set -uo pipefail
: "${LOKALISE_API_TOKEN:?Set LOKALISE_API_TOKEN before running diagnostics}"
: "${LOKALISE_PROJECT_ID:?Set LOKALISE_PROJECT_ID before running diagnostics}"
echo "=== 1. Lokalise API Health ==="
API_STATUS=$(curl -sf -o /dev/null -w "%{http_code}" \
"https://api.lokalise.com/api2/projects/${LOKALISE_PROJECT_ID}" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}")
case "$API_STATUS" in
200) echo "API: HEALTHY (200 OK)" ;;
401) echo "API: AUTH FAILURE (401) — Token invalid or expired. Rotate immediately." ;;
403) echo "API: FORBIDDEN (403) — Token lacks permissions for this project." ;;
404) echo "API: NOT FOUND (404) — Check LOKALISE_PROJECT_ID value." ;;
429) echo "API: RATE LIMITED (429) — Throttled. Wait 10 seconds and retry." ;;
5*) echo "API: LOKALISE OUTAGE (${API_STATUS}) — Check https://status.lokalise.com" ;;
000) echo "API: UNREACHABLE — DNS/network issue. Check connectivity." ;;
*) echo "API: UNEXPECTED (${API_STATUS}) — Investigate further." ;;
esac
echo ""
echo "=== 2. Token Validity ==="
TOKEN_CHECK=$(curl -sf "https://api.lokalise.com/api2/projects/${LOKALISE_PROJECT_ID}" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}" 2>/dev/null)
if [[ $? -eq 0 ]]; then
PROJECT_NAME=$(echo "$TOKEN_CHECK" | jq -r '.project.name')
TEAM_ID=$(echo "$TOKEN_CHECK" | jq -r '.project.team_id')
echo "Token: VALID"
echo " Project: ${PROJECT_NAME}"
echo " Team ID: ${TEAM_ID}"
else
echo "Token: INVALID or project inaccess'Install and configure Lokalise SDK/CLI authentication.
Lokalise Install & Auth
Overview
Set up Lokalise SDK/CLI and configure API token authentication for translation management. Covers the Node.js SDK (@lokalise/node-api v12+), the CLI (lokalise2), and OAuth2 for Lokalise apps.
Prerequisites
- Node.js 18+ (SDK v9+ is ESM-only)
- Package manager (npm, pnpm, or yarn)
- Lokalise account with project access
- API token from Lokalise profile settings
Instructions
Step 1: Install Node.js SDK
set -euo pipefail
# SDK v9+ is ESM-only — requires "type": "module" in package.json or .mjs files
npm install @lokalise/node-api
# For CommonJS projects that cannot migrate to ESM, pin to v8
npm install @lokalise/node-api@8
Step 2: Install CLI Tool
set -euo pipefail
# macOS via Homebrew
brew tap lokalise/cli-2
brew install lokalise2
# Linux — download latest release binary
LATEST_CLI=$(curl -s https://api.github.com/repos/lokalise/lokalise-cli-2-go/releases/latest \
| grep -oP '"tag_name": "\K[^"]+')
curl -sL "https://github.com/lokalise/lokalise-cli-2-go/releases/download/${LATEST_CLI}/lokalise2_linux_x86_64.tar.gz" | tar xz
sudo mv lokalise2 /usr/local/bin/
# Verify installation
lokalise2 --version
Step 3: Generate API Token
- Log into Lokalise
- Click profile avatar > Profile Settings
- Go to API tokens tab
- Click Generate new token
- Choose Read and write for full access (or Read only for CI download pipelines)
- Copy the token immediately (shown only once)
Step 4: Configure Authentication
# Set environment variable (recommended)
export LOKALISE_API_TOKEN="your-api-token"
# Or create .env file for local development
echo 'LOKALISE_API_TOKEN=your-api-token' >> .env
# CLI configuration — creates ~/.lokalise2/config.yml
lokalise2 --token "$LOKALISE_API_TOKEN" project list
Step 5: Verify Connection
import { LokaliseApi } from "@lokalise/node-api";
const lokaliseApi = new LokaliseApi({
apiKey: process.env.LOKALISE_API_TOKEN!,
enableCompression: true, // Gzip responses for faster transfers
});
// Test connection by listing projects
const projects = await lokaliseApi.projects().list({ limit: 10 });
console.log(`Connected! Found ${projects.items.length} projects.`);
for (const p of projects.items) {
console.log(` ${p.project_id}: ${p.name}`);
}
Step 6: OAuth2 Authentication (for Lokalise Apps)
import { LokaliseApiOAuth } from "@lokalise/node-api";
// Use'Configure Lokalise local development with file sync and hot reload.
Lokalise Local Dev Loop
Overview
Set up a complete local development workflow with Lokalise: project structure for i18n files, CLI push/pull commands, file watching for auto-upload, mock translations for offline development, framework integration (React i18next, Vue i18n), and a pre-commit hook to keep translations synced.
Prerequisites
- Lokalise API token exported as
LOKALISEAPITOKEN - Lokalise project ID exported as
LOKALISEPROJECTID - Node.js 18+ with npm or pnpm
lokalise2CLI installed- Git (for pre-commit hook)
Instructions
- Set up the project directory structure for i18n files, compatible with Lokalise's
bundle_structureand most i18n frameworks.
project-root/
├── src/
│ └── locales/
│ ├── en.json # Base language (source of truth)
│ ├── fr.json # Downloaded from Lokalise
│ ├── de.json
│ ├── es.json
│ └── index.ts # Barrel export + type definitions
├── scripts/
│ ├── i18n-push.sh # Upload source to Lokalise
│ ├── i18n-pull.sh # Download translations from Lokalise
│ └── i18n-mock.ts # Generate mock translations
├── .env.local # LOKALISE_API_TOKEN, LOKALISE_PROJECT_ID
└── package.json # i18n:push, i18n:pull, i18n:sync scripts
Barrel export with type safety (src/locales/index.ts):
import en from "./en.json";
// Type derived from base language — all other locales must match this shape
export type TranslationKeys = typeof en;
export const defaultLocale = "en" as const;
export const supportedLocales = ["en", "fr", "de", "es"] as const;
export type Locale = (typeof supportedLocales)[number];
export async function loadLocale(locale: Locale): Promise<TranslationKeys> {
const mod = await import(`./${locale}.json`);
return mod.default;
}
- Create CLI push/pull scripts for the upload-translate-download cycle.
Push script (scripts/i18n-push.sh):
#!/usr/bin/env bash
set -euo pipefail
# Upload source language file to Lokalise
lokalise2 --token "$LOKALISE_API_TOKEN" file upload \
--project-id "$LOKALISE_PROJECT_ID" \
--file ./src/locales/en.json \
--lang-iso en \
--replace-modified \
--include-path \
--detect-icu-plurals \
--poll \
--tag-inserted-keys \
--tag-updated-keys
echo "Source strings pushed to Lokalise"
Pull script (scripts/i18n-pull.sh):
#!/usr/bin/env bash
set -euo pipefail
# Download all translations from Lokalise
lokalise2 --token "$LOKALISE_API_TOKEN"'Execute major migration to Lokalise from other TMS platforms with data.
Lokalise Migration Deep Dive
Current State
!lokalise2 --version 2>/dev/null || echo 'CLI not installed'
!npm list @lokalise/node-api 2>/dev/null | grep lokalise || echo 'SDK not installed'
!node --version 2>/dev/null || echo 'Node.js not available'
Overview
Migrate translations from another TMS (Crowdin, Phrase, POEditor) into Lokalise — export from the source platform, transform key names and variable syntax to match Lokalise conventions, bulk upload via API, validate translation coverage, and handle key conflicts with format-aware tooling.
Prerequisites
- Admin or export access to the source TMS platform
- Lokalise account with a plan that supports the target key count (Free: 500 keys, Pro: unlimited)
LOKALISEAPITOKENenvironment variable set (read-write token)lokalise2CLI or@lokalise/node-apiSDK installedjqfor JSON manipulation during transformation
Instructions
Step 1: Export from Source Platform
Each TMS has its own export format. Export to a Lokalise-compatible format when possible (JSON, XLIFF, or the platform's native format).
From Crowdin:
set -euo pipefail
# Export all translations as JSON (flat key-value structure)
# Use Crowdin CLI or API to download
curl -X POST "https://api.crowdin.com/api/v2/projects/${CROWDIN_PROJECT_ID}/translations/builds" \
-H "Authorization: Bearer ${CROWDIN_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"targetLanguageIds": [], "exportApprovedOnly": false}'
# Download the build when ready (poll build status first)
curl -X GET "https://api.crowdin.com/api/v2/projects/${CROWDIN_PROJECT_ID}/translations/builds/${BUILD_ID}/download" \
-H "Authorization: Bearer ${CROWDIN_TOKEN}" -o crowdin-export.zip
unzip crowdin-export.zip -d crowdin-export/
echo "Exported $(find crowdin-export/ -name '*.json' | wc -l) translation files"
From Phrase (formerly PhraseApp):
set -euo pipefail
# Export all locales as JSON
for LOCALE in en fr de es ja; do
curl -X GET "https://api.phrase.com/v2/projects/${PHRASE_PROJECT_ID}/locales/${LOCALE}/download?file_format=simple_json" \
-H "Authorization: token ${PHRASE_TOKEN}" \
-o "phrase-export/${LOCALE}.json"
sleep 0.5
done
echo "Exported locales: $(ls phrase-export/)"
From POEditor:
set -euo pipefail
# Export via POEditor API (returns a download URL)
EXPORT_URL=$(curl -s -X POST "https://api.poeditor.com/v2/projects/export" \
-d "api_token=${POEDITOR_TOKEN}&id=${POEDITOR_PROJECT_ID}&'Configure Lokalise across development, staging, and production environments.
Lokalise Multi-Environment Setup
Overview
Configure Lokalise for isolated development, staging, and production environments. Two strategies are covered: separate Lokalise projects per environment (strongest isolation) and Lokalise branching within a single project (simpler management). Both approaches include secret management, environment-aware configuration, and a promotion workflow that moves translations through the pipeline from dev to production without cross-contamination.
Prerequisites
- Lokalise Team or Enterprise plan (branching requires Team plan or higher)
- One Lokalise API token per environment, each scoped to minimum required permissions
- Secret management system: GitHub Secrets, AWS Secrets Manager, GCP Secret Manager, or HashiCorp Vault
- Node.js 18+ with
@lokalise/node-apiSDK installed - Environment variable
NODE_ENV(or equivalent) set in each deployment target
Instructions
Step 1: Choose Your Strategy
Option A — Separate projects per environment (recommended for teams > 5 translators or strict compliance):
| Environment | Lokalise Project | Purpose |
|---|---|---|
| Development | MyApp (Dev) |
Rapid iteration, machine translations OK |
| Staging | MyApp (Staging) |
QA review, translator proofing |
| Production | MyApp (Prod) |
Approved translations only |
Option B — Single project with Lokalise branching (simpler for small teams):
| Branch | Purpose |
|---|---|
main |
Production translations |
staging |
QA translations under review |
dev |
Work-in-progress translations |
Step 2: Environment-Aware Configuration
Create a configuration module that selects the correct Lokalise project and credentials based on the runtime environment:
// src/config/lokalise.ts
interface LokaliseEnvConfig {
environment: string;
apiToken: string;
projectId: string;
branch?: string; // Only used with Option B (branching)
cacheTtlMs: number;
enableOta: boolean;
fallbackLocale: string;
rateLimitPerSec: number;
}
const ENV_CONFIGS: Record<string, Omit<LokaliseEnvConfig, 'apiToken' | 'projectId'>> = {
development: {
environment: 'development',
cacheTtlMs: 0, // No cache in dev — always fetch fresh
enableOta: false,
fallbackLocale: 'en',
rateLimitPerSec: 6,
},
staging: {
environment: 'staging',
cacheTtlMs: 5 * 60_000, // 5 minutes
enableOta: true,
'Set up comprehensive observability for Lokalise integrations with metrics,.
Lokalise Observability
Overview
Monitor Lokalise translation pipeline health: API response times, rate limit consumption, translation completion rates, webhook delivery reliability, file upload/download status, and per-word cost tracking. Built around the @lokalise/node-api SDK with Prometheus-compatible metrics and alerting rules.
Prerequisites
@lokalise/node-apiSDK installed- Metrics backend (Prometheus, Datadog, CloudWatch, or OpenTelemetry collector)
- Lokalise API token with read access
- Optional: webhook endpoint for real-time event monitoring
Instructions
Step 1: Instrument API Calls with Metrics
Wrap every SDK call to emit duration, success/failure counts, and rate limit status.
import { LokaliseApi } from "@lokalise/node-api";
interface MetricLabels {
operation: string;
status: "ok" | "error";
code?: string;
}
// Implement this to emit to your metrics backend
declare function emitHistogram(name: string, value: number, labels: MetricLabels): void;
declare function emitCounter(name: string, value: number, labels: MetricLabels): void;
const lok = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
async function trackedApiCall<T>(
operation: string,
fn: () => Promise<T>
): Promise<T> {
const start = performance.now();
try {
const result = await fn();
const durationMs = performance.now() - start;
emitHistogram("lokalise_api_duration_ms", durationMs, {
operation,
status: "ok",
});
emitCounter("lokalise_api_requests_total", 1, {
operation,
status: "ok",
});
return result;
} catch (err: unknown) {
const code = (err as { code?: number })?.code?.toString() ?? "unknown";
const durationMs = performance.now() - start;
emitHistogram("lokalise_api_duration_ms", durationMs, {
operation,
status: "error",
code,
});
emitCounter("lokalise_api_requests_total", 1, {
operation,
status: "error",
code,
});
throw err;
}
}
// Usage — wrap every SDK call
const keys = await trackedApiCall("keys.list", () =>
lok.keys().list({ project_id: projectId, limit: 500 })
);
const bundle = await trackedApiCall("files.download", () =>
lok.files().download(projectId, {
format: "json",
filter_langs: ["en"],
original_filenames: false,
})
);
Step 2: Monitor Translation Completion
Poll project statistics and emit per-locale progress as gauge metrics.
declare function emitGauge(name: string, value: number, labels: Record<string, string>): void;
async function collectTranslationMetrics(projectId: str'Optimize Lokalise API performance with caching, pagination, and bulk.
Lokalise Performance Tuning
Overview
Optimize Lokalise API throughput for translation pipelines by implementing cursor pagination, local caching, batch key operations (500/request), request throttling under the 6 req/s rate limit, and selective language downloads.
Prerequisites
@lokalise/node-apiSDK v9+ (ESM) or REST API accessLOKALISEAPITOKENenvironment variable set- Understanding of project size (key count, language count) to calibrate batch sizes
- Optional: Redis or LRU cache library for persistent caching
Instructions
Step 1: Use Cursor Pagination for Large Datasets
Cursor pagination is significantly faster than offset pagination for projects with 5K+ keys. Offset pagination degrades as page numbers increase because the server must skip rows; cursor pagination uses a pointer.
import { LokaliseApi } from '@lokalise/node-api';
const lok = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
// Generator that yields all keys using cursor pagination
async function* getAllKeys(projectId: string) {
let cursor: string | undefined;
do {
const result = await lok.keys().list({
project_id: projectId,
limit: 500, // Maximum allowed per request
pagination: 'cursor',
cursor,
});
for (const key of result.items) yield key;
cursor = result.hasNextCursor() ? result.nextCursor : undefined;
} while (cursor);
}
// Usage: 10,000 keys = 20 API calls (vs 100 with default limit=100)
let count = 0;
for await (const key of getAllKeys('PROJECT_ID')) {
count++;
}
console.log(`Fetched ${count} keys`);
Offset pagination comparison (avoid for large projects):
| Keys | Offset (limit=100) | Cursor (limit=500) | Time saved |
|---|---|---|---|
| 1,000 | 10 requests | 2 requests | 80% |
| 10,000 | 100 requests | 20 requests | 80% |
| 50,000 | 500 requests (~84s) | 100 requests (~17s) | 80% |
Step 2: Cache Translation Downloads Locally
Translation file downloads are the most expensive Lokalise operation. Cache them locally and use project last_activity timestamps to invalidate.
import { LokaliseApi } from '@lokalise/node-api';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
const lok = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN! });
const CACHE_DIR = '.lokalise-cache';
interface CacheEntry {
url: string;
timestamp: string;
languages: string[];
}
function getCachePath(projectId: string, langIso: string): string {
return `${CACHE_DIR}/${projectId}/${langIso}.json`;
}
'Execute Lokalise production deployment checklist and rollback procedures.
Lokalise Production Checklist
Overview
A structured pre-deployment checklist for Lokalise integrations covering nine verification areas: translation coverage, missing key detection, format validation, API token security, rate limit preparedness, fallback language configuration, download verification, OTA configuration, and contributor access review. Run through each section before any production deployment.
Prerequisites
- Lokalise project with production API token
lokalise2CLI installed and authenticatedcurlandjqavailable in your environment- Access to the Lokalise dashboard (Team Owner or Admin role)
- Application codebase with i18n integration ready for deployment
Instructions
Step 1: Translation Coverage Audit
Verify that every supported locale meets the coverage threshold before deploying.
#!/bin/bash
# scripts/audit-translation-coverage.sh
set -euo pipefail
: "${LOKALISE_API_TOKEN:?Required}"
: "${LOKALISE_PROJECT_ID:?Required}"
REQUIRED_COVERAGE=100 # Percentage required for production
REQUIRED_LOCALES=("en" "de" "fr" "es" "ja")
echo "=== Translation Coverage Audit ==="
# Get project statistics from Lokalise API
STATS=$(curl -sf "https://api.lokalise.com/api2/projects/${LOKALISE_PROJECT_ID}/statistics" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}")
TOTAL_KEYS=$(echo "$STATS" | jq '.project_statistics.keys_total')
echo "Total keys in project: $TOTAL_KEYS"
# Get per-language statistics
LANGUAGES=$(curl -sf "https://api.lokalise.com/api2/projects/${LOKALISE_PROJECT_ID}/languages" \
-H "X-Api-Token: ${LOKALISE_API_TOKEN}")
FAILED=0
echo ""
echo "Locale | Progress | Words | Status"
echo "---------|----------|-----------|-------"
for locale in "${REQUIRED_LOCALES[@]}"; do
progress=$(echo "$LANGUAGES" | jq -r ".languages[] | select(.lang_iso == \"${locale}\") | .statistics.progress")
words=$(echo "$LANGUAGES" | jq -r ".languages[] | select(.lang_iso == \"${locale}\") | .statistics.words_to_do")
if [[ -z "$progress" || "$progress" == "null" ]]; then
echo "${locale} | MISSING | - | FAIL"
FAILED=1
continue
fi
if (( $(echo "$progress < $REQUIRED_COVERAGE" | bc -l) )); then
echo "${locale} | ${progress}% | ${words} remaining | FAIL"
FAILED=1
else
echo "${locale} | ${progress}% | 0 | PASS"
fi
done
echo ""
if [[ $FAILED -eq 1 ]]; then
echo "RESULT: FAILED — Resolve incomplete translations before deploying."
exit 1
fi
echo "RESULT: PASSED — 'Implement Lokalise rate limiting, backoff, and request queuing patterns.
Lokalise Rate Limits
Overview
Lokalise enforces a strict 6 requests per second rate limit across all API endpoints (https://api.lokalise.com/api2). Exceeding this triggers a 429 Too Many Requests response. This skill covers request queuing with 170ms minimum spacing, exponential backoff for 429 recovery, bulk operation throttling, and proactive quota monitoring via response headers.
Prerequisites
@lokalise/node-apiSDK installed (npm install @lokalise/node-api)- API token configured (read or read/write scope depending on operations)
- Node.js 18+ for native
AbortControllersupport in timeout handling
Instructions
1. Understand the Rate Limit Headers
Every Lokalise API response includes rate limit headers:
X-RateLimit-Limit: 6 # Max requests per second
X-RateLimit-Remaining: 4 # Requests remaining in current window
X-RateLimit-Reset: 1700000000 # Unix timestamp when the window resets
Retry-After: 1 # Seconds to wait (only on 429 responses)
Always read these headers. Never hardcode assumptions about the window — Lokalise may adjust limits per plan tier.
2. Implement a Request Queue with 170ms Spacing
Space requests at minimum 170ms apart (1000ms / 6 = ~167ms, rounded up). Use p-queue for concurrency control:
import PQueue from "p-queue";
const lokaliseQueue = new PQueue({
concurrency: 1,
interval: 170,
intervalCap: 1,
});
async function queuedRequest<T>(fn: () => Promise<T>): Promise<T> {
return lokaliseQueue.add(fn, { throwOnTimeout: true });
}
// Usage with the SDK
import { LokaliseApi } from "@lokalise/node-api";
const lokalise = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN });
const keys = await queuedRequest(() =>
lokalise.keys().list({
project_id: "123456789.abcdefgh",
limit: 500,
page: 1,
})
);
3. Add Exponential Backoff for 429 Recovery
When a 429 occurs, honor the Retry-After header first. If absent, use exponential backoff with jitter:
async function withBackoff<T>(
fn: () => Promise<T>,
maxRetries = 5
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error: any) {
if (error.code === 429 && attempt < maxRetries) {
const retryAfter = error.headers?.["retry-after"];
const baseDelay = retryAfter
? parseInt(retryAfter, 10) * 1000
: Math.pow(2, attempt) * 1000;
const jitter = Math.random() * 500;
const delay = baseDelay + jitter;
console.warn(
`Rate limited. Attempt ${attempt + 1}/$'Implement Lokalise reference architecture with best-practice project.
Lokalise Reference Architecture
Overview
A production-ready architecture for integrating Lokalise into web applications. Covers the end-to-end translation flow from source code through CI/CD and Lokalise to deployed translations, recommended project structure for i18n, file organization conventions, multi-app translation sharing, and the tradeoffs between OTA (over-the-air) and build-time translation loading.
Prerequisites
- Node.js 18+ with TypeScript
@lokalise/node-apiSDK installed (npm install @lokalise/node-api)- An i18n framework selected (i18next, react-intl, vue-i18n, or equivalent)
- Lokalise project created with at least one source language configured
- Basic understanding of CI/CD pipelines (GitHub Actions, GitLab CI, or equivalent)
Instructions
Step 1: Architecture Diagram
The translation lifecycle follows this flow:
┌─────────────┐ ┌──────────┐ ┌─────────────┐
│ Source Code │────▶│ CI/CD │────▶│ Lokalise │
│ │ │ (upload) │ │ (TMS) │
│ en.json │ └──────────┘ │ │
│ t('key') │ │ ┌────────┐ │
└─────────────┘ │ │Transla-│ │
│ │ tors │ │
│ └────────┘ │
┌─────────────┐ ┌──────────┐ │ │
│ Deploy │◀────│ CI/CD │◀────│ Download │
│ │ │ (build) │ │ │
│ CDN/Server │ └──────────┘ └─────────────┘
└──────┬──────┘ ┌─────────────┐
│ │ Lokalise │
│ (OTA path) │ OTA CDN │
│◀────────────────────────────│ │
│ └─────────────┘
┌──────▼──────┐
│ Users │
│ (browser/ │
│ mobile) │
└─────────────┘
Two delivery paths:
- Build-time (solid arrows): Translations downloaded during CI build, bundled into the application. Changes require a new deployment.
- OTA (dashed arrow): Translations fetched from Lokalise CDN at runtime. Changes appear without redeployment. Adds a network dependency.
Step 2: Project Structure for i18n
Organize your codebase to separate translation concerns from business logic:
project-root/
├── src/
│ ├── i18n/
│ │ ├── index.ts # i18n initialization and configuration
│ │ ├── client.ts # Lokalise API client wrapper
│ │ ├── loader.ts # Translation loader (build-time or OTA)
│ │ ├── fallback.ts # Fallback translation logic
│ │ ├── types.ts # TypeScript types for translation keys
│ │ └── middleware.ts # Express/Next.js locale detection middleware
│ │
│ ├── locales/
│ │'Apply production-ready Lokalise SDK patterns for TypeScript and Node.
Lokalise SDK Patterns
Overview
Production-grade patterns for @lokalise/node-api: client singleton, cursor pagination, typed error handling, batch operations, upload monitoring, and retry with rate limiting.
Prerequisites
@lokalise/node-apiv12+ installed- TypeScript 5+ with
strictmode
Instructions
- Create a client singleton to centralize configuration and support branch-based project IDs.
// src/lib/lokalise-client.ts
import { LokaliseApi } from "@lokalise/node-api";
let instance: LokaliseApi | null = null;
export function getClient(apiKey?: string): LokaliseApi {
if (instance) return instance;
const key = apiKey ?? process.env.LOKALISE_API_TOKEN;
if (!key) throw new Error("Set LOKALISE_API_TOKEN or pass apiKey");
instance = new LokaliseApi({ apiKey: key, enableCompression: true });
return instance;
}
export function resetClient(): void { instance = null; }
/** Lokalise branch syntax: "projectId:branchName" */
export function projectId(id: string, branch?: string): string {
return branch ? `${id}:${branch}` : id;
}
- Build a cursor-based pagination helper that works with any paginated endpoint.
// src/lib/paginate.ts
interface PaginatedResult<T> {
items: T[];
hasNextCursor(): boolean;
nextCursor(): string;
}
type Fetcher<T> = (params: Record<string, unknown>) => Promise<PaginatedResult<T>>;
/** Async generator yielding all items across pages with rate-limit spacing. */
export async function* paginate<T>(
fetcher: Fetcher<T>,
baseParams: Record<string, unknown>,
pageSize = 500
): AsyncGenerator<T, void, undefined> {
let cursor: string | undefined;
let n = 0;
do {
const params = { ...baseParams, limit: pageSize, ...(cursor ? { cursor } : {}) };
if (n++ > 0) await new Promise((r) => setTimeout(r, 170)); // 6 req/sec
const page = await fetcher(params);
for (const item of page.items) yield item;
cursor = page.hasNextCursor() ? page.nextCursor() : undefined;
} while (cursor);
}
/** Collect all pages into an array (use only when dataset fits in memory). */
export async function paginateAll<T>(fetcher: Fetcher<T>, params: Record<string, unknown>): Promise<T[]> {
const out: T[] = [];
for await (const item of paginate(fetcher, params)) out.push(item);
return out;
}
Usage:
const allKeys = await paginateAll(
(p) => client.keys().list(p),
{ project_id: "123456.abcdef", include_translations: 1 }
);
- Wrap API calls with structured error handling that classifies retryable errors.
// src/lib/lokalise-api.ts
export clas'Apply Lokalise security best practices for API tokens and access control.
Lokalise Security Basics
Overview
Security practices for Lokalise integrations: API token management with scoped permissions, translation content sanitization, CI/CD secret handling, webhook secret verification, and audit logging. Lokalise handles translation strings that may contain user-facing content, interpolation variables, and occasionally PII embedded in keys or values.
Prerequisites
- Lokalise API token provisioned (admin token for audit, scoped tokens for operations)
- Understanding of Lokalise token permission model (read-only vs read-write)
- Secret management infrastructure (GitHub Secrets, AWS Secrets Manager, GCP Secret Manager, or Vault)
Instructions
Step 1: Token Scope Management
Lokalise API tokens are either read-only or read-write. Create separate tokens per use case to enforce least privilege.
import { LokaliseApi } from "@lokalise/node-api";
// Token strategy: separate tokens per context
const TOKENS = {
// CI download pipeline — read-only token
ciDownload: process.env.LOKALISE_READ_TOKEN,
// CI upload pipeline — read-write token
ciUpload: process.env.LOKALISE_WRITE_TOKEN,
// Admin operations (contributor management, webhooks) — admin token
admin: process.env.LOKALISE_ADMIN_TOKEN,
} as const;
function getClient(scope: keyof typeof TOKENS): LokaliseApi {
const token = TOKENS[scope];
if (!token) {
throw new Error(
`LOKALISE_${scope.toUpperCase()}_TOKEN not set. ` +
`Generate at https://app.lokalise.com/profile#apitokens`
);
}
return new LokaliseApi({ apiKey: token, enableCompression: true });
}
// Download translations — uses read-only token
const readClient = getClient("ciDownload");
const bundle = await readClient.files().download(projectId, {
format: "json",
original_filenames: false,
bundle_structure: "%LANG_ISO%.json",
});
Step 2: Validate Translation Content
Translation strings may contain interpolation variables, HTML, or user-generated content. Validate before rendering.
interface ValidationIssue {
key: string;
severity: "critical" | "warning";
message: string;
}
function validateTranslation(key: string, value: string): ValidationIssue[] {
const issues: ValidationIssue[] = [];
// XSS: Check for script injection in translations
if (/<script|javascript:|on\w+=/i.test(value)) {
issues.push({ key, severity: "critical", message: "Potential XSS payload" });
}
// Credential leak: Check for secrets in translation values
if (/(api_key|password|secret|token)\s*[:=]/i.test(value)) {
issues.push({ key, severity: "critical", message: "Possible credential in value" });
}
// Placeholder integrity: Ensure ICU/i18next placeholders are well-formed
const placeholders'Analyze, plan, and execute Lokalise SDK upgrades with breaking change.
Lokalise Upgrade Migration
Current State
!npm list @lokalise/node-api 2>/dev/null | grep lokalise || echo 'SDK not installed'
!lokalise2 --version 2>/dev/null || echo 'CLI not installed'
!node --version 2>/dev/null || echo 'Node.js not available'
!cat package.json 2>/dev/null | grep -E '"type"|"module"' || echo 'No package.json type field'
Overview
Upgrade the @lokalise/node-api SDK between major versions with full breaking change detection, automated code transformation, and verification. The most significant migration is v8 (CommonJS) to v9+ (ESM-only), which requires changes to imports, module configuration, and potentially your build pipeline.
Prerequisites
- Existing project using
@lokalise/node-api(any version 6.x through 9.x) - Node.js 18+ for SDK v9 (Node.js 14+ for v8 and below)
- Git repository with clean working tree (for safe rollback)
- Test suite that exercises Lokalise API calls
Instructions
Step 1: Assess Current Version and Target
set -euo pipefail
echo "=== Current SDK Version ==="
CURRENT=$(npm list @lokalise/node-api --json 2>/dev/null | node -e "
const d = JSON.parse(require('fs').readFileSync(0,'utf8'));
const v = d.dependencies?.['@lokalise/node-api']?.version || 'not found';
console.log(v);
")
echo "Installed: ${CURRENT}"
echo -e "\n=== Latest Available ==="
LATEST=$(npm view @lokalise/node-api version)
echo "Latest: ${LATEST}"
echo -e "\n=== All Major Versions ==="
npm view @lokalise/node-api versions --json | node -e "
const versions = JSON.parse(require('fs').readFileSync(0,'utf8'));
const majors = {};
versions.forEach(v => { const m = v.split('.')[0]; majors[m] = v; });
Object.entries(majors).forEach(([m, v]) => console.log(' v' + m + '.x latest: ' + v));
"
Step 2: Review Breaking Changes by Version
| Version | Node.js | Module System | Key Breaking Changes |
|---|---|---|---|
| 9.x | 18+ | ESM only | require() removed, import only. Pagination returns typed cursors. ApiError export path changed. |
| 8.x | 14+ | CJS + ESM | Last version supporting require(). Constructor accepts apiKey (not token). |
| 7.x | 14+ | CJS | Cursor pagination introduced. list() methods return paginated objects. |
| 6.x | 12+ | CJS | TypeScript rewrite. Method signatures changed from c
lokalise-webhooks-events
View full skill →
'Implement Lokalise webhook handling and event processing.
ReadWriteEditBash(curl:*)
Lokalise Webhooks EventsOverviewLokalise webhooks push real-time notifications to your endpoint when translation events occur — keys created, translations updated, files uploaded, contributors added. This skill covers creating webhooks via the API, handling each event type, verifying webhook secrets, and routing events to appropriate handlers. Prerequisites
Instructions1. Create a Webhook via the APIRegister your endpoint with Lokalise using
The response includes a To scope webhooks to specific languages, use 2. Know the Event Types |