sodcalculator

10 Tech How-To

How to Protect a Translation API Key in Flutter and React

Guide 10-54941 · Updated · Step by step

This guide shows you how to keep your translation API key (like Google Cloud Translation or Azure Translator) out of your Flutter and React app bundles. By the end, you’ll have a working proxy setup that hides the key from users, prevents quota theft, and lets you control costs—without needing a heavy backend framework.

What You’ll Need

  • A translation API account with a valid key (e.g., Google Cloud, Azure, DeepL).
  • A serverless platform account: Vercel, Netlify, Cloudflare Workers, or AWS Lambda. Free tiers work.
  • Node.js installed locally (for testing the proxy before deploying).
  • Your Flutter or React project already set up.

Step-by-Step

  1. Create a serverless function (the proxy). On Vercel, create a folder named api in your project root. Inside, add a file translate.js for React, or for Flutter you can host the same function on any Node.js serverless provider. The function will receive a text and target language from your app, call the translation API with your secret key, and return the result.
  2. Write the proxy code. A minimal example for Vercel/Netlify:
    // api/translate.js
    export default async function handler(req, res) {
      const { text, target } = req.body;
      if (!text || !target) return res.status(400).json({ error: 'Missing fields' });
      const response = await fetch('https://translation.googleapis.com/language/translate/v2', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + process.env.TRANSLATE_KEY },
        body: JSON.stringify({ q: text, target })
      });
      const data = await response.json();
      res.status(200).json(data);
    }

    Replace the URL with your provider’s endpoint. For Azure, use https://api.cognitive.microsofttranslator.com/translate?api-version=3.0 with Ocp-Apim-Subscription-Key header.

  3. Store the key as an environment variable. On Vercel, go to Project Settings → Environment Variables and add TRANSLATE_KEY with your actual key. Never hardcode it in the function. On Netlify, use Site Settings → Environment Variables. For local testing, create a .env file with TRANSLATE_KEY=your_key and load it via dotenv.
  4. Call the proxy from your app. In React, use fetch to POST to /api/translate with the text and target language. In Flutter, use the http or dio package to POST to your deployed URL (e.g., https://your-app.vercel.app/api/translate). Your app never knows the real API key.
  5. Add input validation and rate limiting (recommended). In the proxy, check that the text length is reasonable (e.g., under 5000 characters), and optionally use a simple in-memory rate limiter or a third-party service like Upstash Redis to limit requests per IP. This prevents abuse if someone discovers your proxy endpoint.
  6. Deploy and test. Push your code to your hosting platform. Test the endpoint with a tool like Postman or curl, sending a sample request. Then test from your app to confirm it works end-to-end.
  7. For Flutter specifically, ensure you don’t accidentally include the key in the app bundle. Do not store the key in String.fromEnvironment or in a Dart file that gets compiled into the app. Only the proxy URL goes into your Flutter code.

Common Mistakes

  • Hardcoding the key in the app. Even if you obfuscate it, anyone can decompile the app and extract it.
  • Putting the key in a public GitHub repo. Use environment variables and never commit .env files.
  • Exposing the proxy without any limits. A publicly callable proxy lets anyone burn your quota. Add authentication (e.g., a simple app-specific token) or rate limiting.
  • Using the wrong API endpoint. Double-check the URL and headers for your provider. A common mistake is using the v2 endpoint when you have a v3 key.
  • Forgetting to enable CORS. If your React app runs on a different domain than the proxy, you’ll get CORS errors. On Vercel, add CORS headers in the function response: res.setHeader('Access-Control-Allow-Origin', '*') for development, but restrict it to your domain in production.

Tips

  • Use a dedicated API key for this project only, so you can revoke it without affecting other services.
  • Set a monthly budget alert on your translation provider to avoid surprise bills.
  • Cache translations on the client side (e.g., in a local database) to reduce API calls.
  • For Flutter, consider using a package like flutter_dotenv to load the proxy URL from a config file, but never the API key itself.
  • If you need higher security, add a simple authentication layer to your proxy: require a custom header like X-App-Token that your app sends, and validate it in the function.
  • Use environment variables for the proxy URL as well, so you can switch between development and production easily.

Troubleshooting

I get CORS errors in React. Add the appropriate CORS headers in your serverless function. For Vercel, you can also use a vercel.json file with headers config, but the simplest is to set them in the function response.

My Flutter app gets a 404 when calling the proxy. Check the URL path. On Vercel, a file in api/translate.js is served at /api/translate. Make sure you’re using the full deployed URL, not localhost.

The proxy returns 401 or 403. Your API key is likely invalid or not set correctly in the environment variable. Check the provider’s error message and verify the key has the right permissions.

Local testing works but deployed version fails. Ensure you’ve added the environment variable in your hosting platform’s dashboard, and that the function is using process.env.TRANSLATE_KEY correctly.

Requests are slow. Translation APIs can take a few seconds. Consider adding a timeout in your app (e.g., 10 seconds) and showing a loading state. Also, check if your provider has a faster region or tier.

The proxy works but I’m worried about abuse. Implement rate limiting. A simple approach is to use a global counter per IP in a store like Cloudflare KV or Upstash, but for a small app, a basic in-memory limiter (with a warning that it resets on restart) is enough to start.

Frequently Asked Questions

Can I hide the API key in Flutter without a backend?

No. Any key embedded in the app binary can be extracted. A serverless proxy is the minimum viable solution.

Is a serverless function free?

Most platforms offer a free tier with limited invocations. For low-traffic personal projects, it’s usually enough. Check your provider’s current pricing.

What if I use Firebase? Can I use Cloud Functions?

Yes. Firebase Cloud Functions work the same way. Create a function that calls the translation API, and call it from your app using the Firebase SDK.

Can I use a third-party service like a translation API gateway?

Yes, some services offer built-in key protection and usage analytics, but they add cost. The proxy approach is more flexible and works with any provider.

Do I need to worry about the proxy URL being public?

Yes, but it’s safer than exposing the key. You can add a simple app secret or use Firebase Authentication to restrict access to your function.

What if my translation provider doesn’t support server-side calls?

All major translation APIs (Google, Azure, DeepL, AWS) support server-side calls. If yours doesn’t, switch to one that does.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →