How to Integrate Baidu Translate API for Article Translation in a Nuxt App: A Complete Guide
Integrate Baidu Translate API in a Nuxt application by using the Baidu driver class from app/libs/translate/baidu.ts, configuring a Nitro dev proxy in nuxt.config.ts, and calling the translate() method with your appid and key credentials.
This tutorial walks through the production-ready implementation found in the zyronon/TypeWords repository, demonstrating how to securely translate article content without exposing API credentials to the client.
Why Use a Proxy for Baidu Translation?
Baidu Translate API requires an appid and secret key for request signing. Exposing these credentials in client-side code creates security risks. The TypeWords solution routes all translation requests through a Nuxt Nitro dev proxy, keeping credentials server-side while allowing seamless frontend integration.
Step 1: Configure the Nuxt Dev Proxy
In nuxt.config.ts, add a devProxy entry that forwards /baidu requests to Baidu's official translation endpoint:
export default defineNuxtConfig({
// ... other config
nitro: {
devProxy: {
'/baidu': {
target: 'https://api.fanyi.baidu.com/api/trans/vip/translate',
changeOrigin: true,
},
},
},
})
This configuration ensures all requests to /baidu are transparently forwarded to https://api.fanyi.baidu.com/api/trans/vip/translate with proper origin headers.
Step 2: Understand the Baidu Driver Architecture
The Baidu class in app/libs/translate/baidu.ts implements a generic Translator interface. It handles four critical responsibilities:
- Request signing: Generates MD5 signatures required by Baidu's API
- Language mapping: Converts between ISO codes (
en,zh-CN) and Baidu's internal codes (en,zh) - Response parsing: Transforms Baidu's JSON into a unified
TranslateQueryResult - Text-to-speech URLs: Generates Baidu TTS endpoints for audio playback
Core Translation Method Signature
translate(text: string, from: string, to: string): Promise<TranslateQueryResult>
The method returns an object containing:
trans.paragraphs: Array of translated text segmentstrans.orig: Original textfrom: Detected source language (after mapping)phonetic: Phonetic representation (when available)trans.tts: TTS URL for translated textorig.tts: TTS URL for original text
Step 3: Import and Instantiate the Baidu Driver
In your Nuxt component or composable, import from the unified library entry point:
import Baidu from '@/libs/translate/baidu'
const baidu = new Baidu({
appid: process.env.BAIDU_APP_ID!, // Your Baidu appid
key: process.env.BAIDU_API_KEY!, // Your Baidu secret key
})
Environment variables keep credentials out of version control. In production, set these via your hosting platform's secret management.
Step 4: Translate Article Content
Call translate() with article text, source language, and target language:
// Translate from auto-detected language to English
const result = await baidu.translate(
'今天天气很好,适合外出散步。',
'auto',
'en'
)
console.log(result.trans.paragraphs)
// Output: ['The weather is nice today, suitable for going out for a walk.']
console.log(result.from)
// Output: 'zh'
The from: 'auto' parameter triggers Baidu's automatic language detection. Specify exact codes like 'zh-CN' or 'en' for explicit source control.
Step 5: Integrate into Article Editing Pages
The EditArticle.vue component demonstrates real-world integration. It maintains a networkTranslateEngine state defaulting to "baidu":
<script setup lang="ts">
import { ref } from 'vue'
import Baidu from '@/libs/translate/baidu'
const articleContent = ref('')
const isTranslating = ref(false)
const baidu = new Baidu({
appid: useRuntimeConfig().baiduAppId,
key: useRuntimeConfig().baiduApiKey,
})
async function translateArticle() {
if (!articleContent.value.trim()) return
isTranslating.value = true
try {
const { trans, from } = await baidu.translate(
articleContent.value,
'auto',
'en'
)
// Replace content with translated paragraphs
articleContent.value = trans.paragraphs.join('\n\n')
console.log(`Translated from ${from} to en`)
} catch (err) {
console.error('Translation failed:', err)
} finally {
isTranslating.value = false
}
}
</script>
<template>
<div class="article-editor">
<textarea v-model="articleContent" rows="20" />
<button
@click="translateArticle"
:disabled="isTranslating"
>
{{ isTranslating ? 'Translating...' : 'Translate via Baidu' }}
</button>
</div>
</template>
Step 6: Add Text-to-Speech Support
The driver includes a textToSpeech() method for generating pronunciation URLs:
// Get TTS URL for translated text
const ttsUrl = await baidu.textToSpeech('Hello world', 'en')
// Returns: https://fanyi.baidu.com/gettts?lan=en&text=Hello%20world&spd=5
// Play audio in browser
const audio = new Audio(ttsUrl)
audio.play()
This feature enhances accessibility and language learning use cases within your article platform.
How Request Signing Works (Security Deep-Dive)
Baidu requires every API call to include a signature. The driver automatically generates this in app/libs/translate/baidu.ts:
// Pseudocode of the signing process
const salt = randomString()
const sign = md5(appid + text + salt + key)
const params = { appid, q: text, salt, sign, from, to }
The proxy forwards this signed request to Baidu, validating your credentials without exposing the secret key to the browser.
Language Code Reference
| ISO Code | Baidu Code | Description |
|---|---|---|
zh, zh-CN |
zh |
Simplified Chinese |
zh-TW, zh-HK |
cht |
Traditional Chinese |
en |
en |
English |
ja |
jp |
Japanese |
ko |
kor |
Korean |
fr |
fra |
French |
es |
spa |
Spanish |
de |
de |
German |
The driver automatically handles bidirectional mapping via internal langMap and langMapReverse objects.
Summary
- Configure the proxy in
nuxt.config.tsto route/baiduto Baidu's API endpoint - Import the driver from
app/libs/translate/baidu.tsand instantiate with credentials - Call
translate()with text, source language, and target language parameters - Handle results via the standardized
TranslateQueryResultinterface - Secure credentials through environment variables and server-side proxying
Frequently Asked Questions
How do I obtain Baidu Translate API credentials?
Register at Baidu Translate Open Platform, create a new application, and receive an appid and secret key. Standard accounts include free monthly quotas; upgrade for higher volume.
Why does my translation return "Invalid sign" errors?
This typically occurs from incorrect credential configuration, system clock drift, or unsupported characters in the text parameter. Verify your appid and key match exactly, ensure your server time is synchronized, and URL-encode special characters before sending.
Can I use this implementation in production with server-side rendering?
Yes. The Nitro dev proxy works in development. For production, configure the equivalent proxy rules in your reverse proxy (Nginx, Cloudflare) or use Nuxt's server/api routes to create a secure API endpoint that forwards requests to Baidu with proper signing.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →