Translation API for Node.js
This guide shows you how to use the Langbly translation API in Node.js and TypeScript. Langbly is a Google Translate v2 compatible API with context-aware translation quality, 81–90% cheaper than Google Translate.
Installation
npm install langbly
# or
yarn add langbly
# or
pnpm add langbly
Quick Start
import { Langbly } from 'langbly';
const client = new Langbly({ apiKey: 'your-api-key-here' });
const result = await client.translate({
q: 'Hello, how are you?',
target: 'nl',
});
console.log(result.translatedText);
// Output: "Hallo, hoe gaat het met je?"
Get Your API Key
- Sign up at langbly.com/signup (free, no credit card)
- Create an API key in your dashboard
- Free tier includes 500K characters/month
Translate Text
Basic Translation
import { Langbly } from 'langbly';
const client = new Langbly({ apiKey: 'your-api-key-here' });
// English to Dutch
const result = await client.translate({ q: 'Good morning!', target: 'nl' });
console.log(result.translatedText); // "Goedemorgen!"
// English to German
const result2 = await client.translate({ q: 'Good morning!', target: 'de' });
console.log(result2.translatedText); // "Guten Morgen!"
With Source Language
const result = await client.translate({
q: 'Bonjour le monde',
target: 'en',
source: 'fr',
});
console.log(result.translatedText); // "Hello world"
HTML Translation
const result = await client.translate({
q: '<p>Welcome to our <strong>website</strong></p>',
target: 'nl',
format: 'html',
});
console.log(result.translatedText);
// "<p>Welkom op onze <strong>website</strong></p>"
Batch Translation
Translate multiple strings in a single API call:
const results = await client.translate({
q: ['Hello', 'Goodbye', 'Thank you'],
target: 'nl',
});
results.forEach((r) => console.log(r.translatedText));
// "Hallo"
// "Tot ziens"
// "Dank je"
Error Handling
The SDK provides typed error classes:
import { Langbly, AuthenticationError, RateLimitError } from 'langbly';
const client = new Langbly({ apiKey: 'your-api-key-here' });
try {
const result = await client.translate({ q: 'Hello', target: 'nl' });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else {
console.error('Error:', error);
}
}
Auto-Retry
The SDK automatically retries on 429 and 5xx errors with exponential backoff:
const client = new Langbly({
apiKey: 'your-api-key-here',
maxRetries: 3, // default
});
Integration Examples
Express.js Middleware
import express from 'express';
import { Langbly } from 'langbly';
const app = express();
const langbly = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
app.post('/api/translate', express.json(), async (req, res) => {
const { text, target, source } = req.body;
const result = await langbly.translate({
q: text,
target,
source,
});
res.json({ translation: result.translatedText });
});
Next.js API Route
// app/api/translate/route.ts
import { Langbly } from 'langbly';
import { NextRequest, NextResponse } from 'next/server';
const langbly = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
export async function POST(request: NextRequest) {
const { text, target } = await request.json();
const result = await langbly.translate({
q: text,
target,
});
return NextResponse.json({ translation: result.translatedText });
}
Translate i18n JSON File
import { readFileSync, writeFileSync } from 'fs';
import { Langbly } from 'langbly';
const client = new Langbly({ apiKey: process.env.LANGBLY_API_KEY! });
async function translateI18n(inputFile: string, outputFile: string, targetLang: string) {
const source = JSON.parse(readFileSync(inputFile, 'utf-8'));
const keys = Object.keys(source);
const values = Object.values(source) as string[];
const results = await client.translate({ q: values, target: targetLang });
const translated: Record<string, string> = {};
keys.forEach((key, i) => {
translated[key] = results[i].translatedText;
});
writeFileSync(outputFile, JSON.stringify(translated, null, 2));
console.log(`Translated ${keys.length} keys to ${targetLang}`);
}
// Usage
await translateI18n('locales/en.json', 'locales/nl.json', 'nl');
Environment Variables
export LANGBLY_API_KEY=your-api-key-here
// Automatically reads LANGBLY_API_KEY from environment
const client = new Langbly();
TypeScript Support
The SDK is written in TypeScript with full type definitions:
import { Langbly, TranslateResult, LangblyError } from 'langbly';
const client = new Langbly({ apiKey: 'your-key' });
// TranslateResult is fully typed
const result: TranslateResult = await client.translate({
q: 'Hello',
target: 'nl',
});
Google Translate Migration
// Before (Google Translate)
// import { v2 } from '@google-cloud/translate';
// const client = new v2.Translate({ key: 'GOOGLE_KEY' });
// const [translation] = await client.translate('Hello', 'nl');
// After (Langbly) - same concept, simpler API
import { Langbly } from 'langbly';
const client = new Langbly({ apiKey: 'your-key' });
const result = await client.translate({ q: 'Hello', target: 'nl' });
console.log(result.translatedText);