Adding multilingual support to a JavaScript application is one of the most impactful features you can ship. Whether you're building a SaaS product, an e-commerce platform, or an internal tool, a translation API lets you serve users in their native language without hiring translators for every string.
This tutorial walks through three approaches to integrating a translation API into JavaScript and Node.js applications. We'll cover the Langbly SDK, direct HTTP requests with fetch, and Google's official client library. Every code example is production-ready and includes error handling.
By the end, you'll have a working translation integration you can use in Node.js backends, Next.js apps, Express servers, or serverless functions.
Prerequisites
Before starting, make sure you have:
- Node.js 18 or later. We use the built-in
fetchAPI, which requires Node 18+. Check your version withnode --version. - npm or yarn for installing packages.
- A Langbly API key. Sign up at langbly.com/signup to get a free API key. The free tier includes 500,000 characters per month.
If you want to follow along with the Google SDK example, you'll also need a Google Cloud project with the Translation API enabled and a valid API key.
Option 1: Using Langbly's Node.js SDK
The fastest way to add translation to a JavaScript project is with the Langbly Node.js SDK. It provides a typed client with built-in retry logic and error handling.
Installation
npm install langbly
Basic translation
import Langbly from 'langbly';
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY });
// Translate a single string
const result = await client.translate({
q: 'Your order has been shipped.',
target: 'de',
source: 'en',
});
console.log(result.translatedText);
// "Ihre Bestellung wurde versandt."
Detect language
If you don't know the source language, omit the source parameter. The API will detect it automatically and return the detected language code in the response:
const result = await client.translate({
q: 'Bonjour le monde',
target: 'en',
});
console.log(result.translatedText);
// "Hello world"
console.log(result.detectedSourceLanguage);
// "fr"
Translate HTML
To translate content that contains HTML tags, set format to "html". The API will preserve all markup and only translate the visible text:
const result = await client.translate({
q: '<h1>Welcome</h1><p>Browse our <strong>latest products</strong>.</p>',
target: 'fr',
format: 'html',
});
console.log(result.translatedText);
// "<h1>Bienvenue</h1><p>Parcourez nos <strong>derniers produits</strong>.</p>"
Batch translation
You can translate multiple strings in a single API call by passing an array to q. This reduces HTTP overhead and is the recommended approach when you have multiple strings to translate:
const results = await client.translate({
q: ['Add to cart', 'Checkout', 'Your order is confirmed'],
target: 'es',
source: 'en',
});
results.forEach((r) => console.log(r.translatedText));
// "Agregar al carrito"
// "Pagar"
// "Su pedido ha sido confirmado"
TypeScript support
The SDK includes full TypeScript type definitions out of the box. Here's an example with explicit typing:
import Langbly from 'langbly';
import type { TranslateResponse } from 'langbly';
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
interface ProductTranslation {
title: string;
description: string;
}
async function translateProduct(
title: string,
description: string,
targetLang: string
): Promise<ProductTranslation> {
const results = await client.translate({
q: [title, description],
target: targetLang,
source: 'en',
});
return {
title: results[0].translatedText,
description: results[1].translatedText,
};
}
const translated = await translateProduct(
'Wireless Bluetooth Headphones',
'Premium sound quality with 30-hour battery life.',
'ja'
);
console.log(translated.title);
// "ワイヤレスBluetoothヘッドフォン"
Option 2: Using fetch Directly
If you prefer not to install an SDK, you can call the translation API directly with fetch. Langbly uses the Google Translate v2 request format, so the endpoint and parameters are familiar to anyone who has worked with Google's API.
const API_KEY = process.env.LANGBLY_API_KEY;
const BASE_URL = 'https://api.langbly.com/language/translate/v2';
async function translate(text, targetLang, sourceLang = 'en') {
const response = await fetch(BASE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: text,
target: targetLang,
source: sourceLang,
format: 'text',
key: API_KEY,
}),
});
if (!response.ok) {
throw new Error(`Translation failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.data.translations[0].translatedText;
}
// Usage
const translated = await translate('Hello, world!', 'nl');
console.log(translated);
// "Hallo, wereld!"
This approach works in both Node.js 18+ (which includes a built-in fetch) and in the browser. For browser usage, remember that your API key will be exposed in client-side code. Always proxy translation requests through your backend in production.
Batch translation with fetch
async function translateBatch(texts, targetLang) {
const response = await fetch(BASE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: texts,
target: targetLang,
format: 'text',
key: API_KEY,
}),
});
const data = await response.json();
return data.data.translations.map((t) => t.translatedText);
}
const results = await translateBatch(
['Sign up', 'Log in', 'Forgot password?'],
'de'
);
console.log(results);
// ["Registrieren", "Anmelden", "Passwort vergessen?"]
Option 3: Using Google's Official SDK
If you're already using Google Cloud services, you can use their official @google-cloud/translate package. The setup is more involved because it requires a Google Cloud project and service account:
npm install @google-cloud/translate
const { Translate } = require('@google-cloud/translate').v2;
// Requires GOOGLE_APPLICATION_CREDENTIALS env var pointing to
// a service account JSON file, or explicit project configuration
const translate = new Translate({
projectId: 'your-gcp-project-id',
key: 'YOUR_GOOGLE_API_KEY',
});
async function translateText(text, targetLang) {
const [translation] = await translate.translate(text, targetLang);
return translation;
}
const result = await translateText('Hello, world!', 'nl');
console.log(result);
// "Hallo, wereld!"
The Google SDK handles authentication and retries internally, but requires more setup. You need a Google Cloud project, billing enabled, and the Translation API activated. For a detailed walkthrough, see our Google Translate API guide.
Switching from Google to Langbly is a one-line change if you're using the raw fetch approach. Just change the base URL from translation.googleapis.com to api.langbly.com. The request and response format is identical.
Error Handling and Retries
Production translation integrations need robust error handling. The two most common issues are rate limiting (HTTP 429) and temporary server errors (HTTP 5xx). Here's a reusable wrapper with exponential backoff:
async function translateWithRetry(text, targetLang, maxRetries = 3) {
const API_KEY = process.env.LANGBLY_API_KEY;
const BASE_URL = 'https://api.langbly.com/language/translate/v2';
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const response = await fetch(BASE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: text,
target: targetLang,
format: 'text',
key: API_KEY,
}),
});
if (response.ok) {
const data = await response.json();
return data.data.translations[0].translatedText;
}
// Rate limited or server error - retry with backoff
if (response.status === 429 || response.status >= 500) {
if (attempt === maxRetries) {
throw new Error(`Translation failed after ${maxRetries} retries: ${response.status}`);
}
// Respect Retry-After header if present
const retryAfter = response.headers.get('Retry-After');
const delay = retryAfter
? parseInt(retryAfter, 10) * 1000
: Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
// Client error - don't retry
const errorBody = await response.text();
throw new Error(`Translation error ${response.status}: ${errorBody}`);
}
}
// Usage
try {
const translated = await translateWithRetry('Hello!', 'fr');
console.log(translated);
} catch (err) {
console.error('Translation failed:', err.message);
}
If you use the Langbly Node.js SDK, retry logic with exponential backoff is built in. The SDK automatically retries on 429 and 5xx responses, respects Retry-After headers, and throws typed errors (RateLimitError, AuthenticationError) so you can handle each case explicitly.
Using Translation in React and Next.js
In React and Next.js applications, translations should always happen on the server side. This keeps your API key secure and avoids client-side latency. Here are two patterns that work well.
Next.js Server Component (App Router)
// app/products/[id]/page.tsx
import Langbly from 'langbly';
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
export default async function ProductPage({
params,
searchParams,
}: {
params: { id: string };
searchParams: { lang?: string };
}) {
const product = await getProduct(params.id);
const targetLang = searchParams.lang || 'en';
let title = product.title;
let description = product.description;
if (targetLang !== 'en') {
const results = await client.translate({
q: [product.title, product.description],
target: targetLang,
source: 'en',
});
title = results[0].translatedText;
description = results[1].translatedText;
}
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
Next.js API Route
// app/api/translate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import Langbly from 'langbly';
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
export async function POST(request: NextRequest) {
const { text, targetLang } = await request.json();
const result = await client.translate({
q: text,
target: targetLang,
});
return NextResponse.json({
translatedText: result.translatedText,
detectedSourceLanguage: result.detectedSourceLanguage,
});
}
Express middleware
For Express applications, you can create a translation middleware that translates response bodies based on the Accept-Language header:
import express from 'express';
import Langbly from 'langbly';
const app = express();
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY });
app.post('/api/translate', async (req, res) => {
try {
const { text, target, source } = req.body;
const result = await client.translate({
q: text,
target,
source,
});
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000);
Best Practices
Cache translations aggressively
Translation results are deterministic for the same input. Cache them to avoid paying for the same translation twice. A simple in-memory cache works for small apps. For larger applications, use Redis or a database:
const cache = new Map();
async function translateCached(text, targetLang) {
const key = `${targetLang}:${text}`;
if (cache.has(key)) {
return cache.get(key);
}
const result = await client.translate({
q: text,
target: targetLang,
});
cache.set(key, result.translatedText);
return result.translatedText;
}
Batch requests whenever possible
Instead of making one API call per string, batch multiple strings into a single request. The API accepts an array of strings in the q parameter. This reduces HTTP overhead and is faster overall.
Use TypeScript for type safety
The Langbly SDK includes full TypeScript types. If you're using TypeScript, you get autocomplete for all parameters and typed error classes. This catches integration mistakes at compile time rather than in production.
Never expose your API key client-side
Always proxy translation requests through your backend. If your API key is embedded in browser JavaScript, anyone can inspect the network tab and use your key. Create a backend endpoint (see the Express or Next.js API route examples above) and call that from your frontend.
Handle HTML content correctly
When translating HTML, always set format: "html". This ensures the API preserves tags, attributes, and structure while only translating the visible text. If you send HTML with format: "text", tags may be translated or corrupted.
Pricing for JavaScript Developers
Here's how the major translation APIs compare for a typical JavaScript project:
| Provider | 5M chars/mo | 25M chars/mo | 100M chars/mo | Free tier |
|---|---|---|---|---|
| Langbly | $19/mo | $69/mo | $199/mo | 500K chars/mo |
| Google Translate API | $100/mo | $500/mo | $2,000/mo | 500K chars/mo |
| DeepL API | $25/mo + usage | $25/mo + usage | $25/mo + usage | 500K chars/mo |
| Amazon Translate | $75/mo | $375/mo | $1,500/mo | 2M chars/mo (12 months) |
Langbly is the most cost-effective option for JavaScript developers at every volume tier. The free tier lets you build and test your integration without entering a credit card. When you're ready for production, the Starter plan at $19/month covers 5 million characters, which is enough for most SaaS applications.
For high-volume applications like e-commerce platforms or content management systems that need 100 million characters or more, Langbly's Scale plan at $199/month represents a 90% cost saving compared to Google Translate.
Summary
Adding translation to a JavaScript application takes minutes with the right API. Here's a quick comparison of the three approaches we covered:
| Approach | Setup time | TypeScript | Auto-retry | Best for |
|---|---|---|---|---|
| Langbly SDK | 2 minutes | Built-in | Built-in | Production apps |
| Raw fetch | 5 minutes | Manual | Manual | Minimal dependencies |
| Google SDK | 15+ minutes | Partial | Built-in | Existing GCP users |
The Langbly SDK gives you the best developer experience with the least setup. If you're starting a new project or looking to switch from Google Translate, you can be up and running with npm install langbly and three lines of code.
Related Articles
- Google Translate API for Developers: A Complete Guide. Detailed walkthrough of Google Translate API setup, authentication, and code examples.
- How to Cut Your Translation API Costs by 90%. Full pricing analysis comparing Google Translate, DeepL, and Langbly at different monthly volumes.
- LLM vs Neural Machine Translation. Understand why advanced translation produces more natural output than traditional NMT engines.