Google Cloud Translation API in Node.js: Setup Guide
In this article
This guide walks you through integrating the Google Cloud Translation API into a Node.js application. By the end, you'll be able to send text to Google's translation service and receive translations in dozens of languages, all from your backend. You'll need a Google Cloud project with billing enabled, the Cloud Translation API activated, and a service account key file for authentication.
What You'll Need
- Node.js (version 14 or later) installed on your machine
- A Google Cloud project with billing enabled (required for API access)
- The Cloud Translation API enabled in that project
- A service account key file (JSON) downloaded from Google Cloud Console
- Basic familiarity with npm and command line
Step-by-Step
- Set up your Google Cloud project
Go to the Google Cloud Console, create a new project or select an existing one. Ensure billing is linked to the project. Then navigate to "APIs & Services" > "Library" and search for "Cloud Translation API". Click on it and press "Enable".
- Create a service account and download the key
In the Console, go to "APIs & Services" > "Credentials". Click "Create Credentials" and choose "Service Account". Give it a name (e.g., "translation-service"), assign the role "Cloud Translation API User" (or a custom role with translation permissions), and click "Done". Then, in the service account list, click the three-dot menu and select "Manage Keys". Click "Add Key" > "Create New Key", choose JSON, and download the file. Keep it safeāthis is your authentication secret.
- Initialize your Node.js project
Create a new directory for your project and run
npm init -yto generate a package.json. Then install the Google Cloud Translation client library:npm install @google-cloud/translate. - Set up environment variables
For security, store your service account key path in an environment variable. Create a
.envfile in your project root (if you have dotenv installed) or set it directly in your shell. Example:GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/key.json". If you prefer, you can hardcode the path in your code, but avoid committing the key file to version control. - Write a translation function
Create a file, e.g.,
translate.js. Require the library and instantiate a client. Here's a minimal example:const { TranslationServiceClient } = require('@google-cloud/translate'); const client = new TranslationServiceClient(); async function translateText(text, targetLang) { const request = { parent: 'projects/your-project-id/locations/global', contents: [text], mimeType: 'text/plain', targetLanguageCode: targetLang, }; const [response] = await client.translateText(request); return response.translations[0].translatedText; } module.exports = translateText; - Use the function in your app
In your main server file (e.g.,
app.js), import and call the function. For example, with Express:const express = require('express'); const translateText = require('./translate'); const app = express(); app.use(express.json()); app.post('/translate', async (req, res) => { const { text, target } = req.body; try { const translated = await translateText(text, target); res.json({ translated }); } catch (err) { res.status(500).json({ error: err.message }); } }); app.listen(3000, () => console.log('Server running on port 3000')); - Test your implementation
Run your server with
node app.jsand send a POST request to/translatewith a JSON body like{"text":"Hello world","target":"es"}. You should receive{"translated":"Hola mundo"}. Use curl or Postman for testing.
Common Mistakes
- Forgetting to enable billing: The Translation API requires billing to be enabled. If you skip this, you'll get a 403 or billing-related errors.
- Hardcoding the service account key path: This is a security risk and also makes your code less portable. Always use environment variables.
- Using the wrong project ID: In the
parentfield, you must use your actual Google Cloud project ID, not the project name. Check it in the Console. - Ignoring the location: The parent field must include a location. Using
globalis fine for most cases, but some regions may require specific locations. - Not handling errors: Network issues or invalid input will throw errors. Always wrap API calls in try/catch and return meaningful error messages.
Tips
- Use the v3 API: The
@google-cloud/translatelibrary uses the v3 API, which is more feature-rich and supports glossaries and batch translation. - Cache translations: If you're translating the same text repeatedly, consider caching results in memory or a database to reduce API calls and costs.
- Detect language automatically: You can omit
sourceLanguageCodeand let the API detect the source language. This is useful for user-generated content. - Use glossaries for domain-specific terms: If you're translating technical or brand-specific terms, create a glossary in the Cloud Console and reference it in your request.
- Set a timeout: API calls can hang if there's a network issue. Set a timeout on your HTTP client to fail gracefully.
Troubleshooting
- 403 Permission Denied: Check that your service account has the correct role. Also verify the key file path is correct and the environment variable is set.
- Project not found: Ensure the project ID in the parent field matches the project ID in the Console, not the project name.
- Billing not enabled: Go to the Billing section in the Console and confirm that billing is active for your project. You'll see a specific error message if this is the cause.
- Module not found: If you get
Cannot find module '@google-cloud/translate', runnpm installagain in the correct directory. - Invalid target language code: Make sure you're using ISO 639-1 codes like 'es', 'fr', 'de'. The API will return an error if the code is invalid.
- Network issues: If you're behind a proxy or firewall, the API call might fail. Test with a simple curl to the Google API endpoint to isolate the issue.
Frequently Asked Questions
How do I get the source language of the text?
Omit the sourceLanguageCode field in your request. The API will auto-detect it and return it in the response as detectedLanguageCode.
Can I translate multiple strings at once?
Yes, the contents field accepts an array of strings. The API returns an array of translations in the same order.
Is there a free tier for the Translation API?
Google Cloud offers a free tier for Translation API, typically 500,000 characters per month. Beyond that, you pay per character. Check the current pricing page for exact limits.
How do I translate HTML content without breaking the markup?
Set mimeType to 'text/html' in your request. The API will preserve the HTML structure and translate only the visible text.
Can I use this API in a browser environment?
It's not recommended because you'd expose your service account credentials. Instead, create a backend endpoint that calls the API and have your frontend communicate with that endpoint.
What if I need to translate a large file?
For large batches, consider using the Batch Translation feature, which processes files from Google Cloud Storage asynchronously. This is more efficient for big volumes.