# How to Integrate Baidu Translate API for Article Translation in a Nuxt App: A Complete Guide

> Learn to integrate Baidu Translate API in your Nuxt app. This guide shows how to use the Baidu driver, configure a Nitro dev proxy, and implement translation for your articles.

- Repository: [Zyronon/TypeWords](https://github.com/zyronon/TypeWords)
- Tags: how-to-guide
- Published: 2026-09-03

---

**Integrate Baidu Translate API in a Nuxt application by using the `Baidu` driver class from [`app/libs/translate/baidu.ts`](https://github.com/zyronon/TypeWords/blob/main/app/libs/translate/baidu.ts), configuring a Nitro dev proxy in [`nuxt.config.ts`](https://github.com/zyronon/TypeWords/blob/main/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`](https://github.com/zyronon/TypeWords/blob/main/nuxt.config.ts), add a `devProxy` entry that forwards `/baidu` requests to Baidu's official translation endpoint:

```typescript
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`](https://github.com/zyronon/TypeWords/blob/main/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

```typescript
translate(text: string, from: string, to: string): Promise<TranslateQueryResult>

```

The method returns an object containing:
- `trans.paragraphs`: Array of translated text segments
- `trans.orig`: Original text
- `from`: Detected source language (after mapping)
- `phonetic`: Phonetic representation (when available)
- `trans.tts`: TTS URL for translated text
- `orig.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:

```typescript
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:

```typescript
// 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`](https://github.com/zyronon/TypeWords/blob/main/EditArticle.vue) component demonstrates real-world integration. It maintains a `networkTranslateEngine` state defaulting to `"baidu"`:

```vue
<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:

```typescript
// 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`](https://github.com/zyronon/TypeWords/blob/main/app/libs/translate/baidu.ts):

```typescript
// 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.ts`](https://github.com/zyronon/TypeWords/blob/main/nuxt.config.ts) to route `/baidu` to Baidu's API endpoint
- **Import the driver** from [`app/libs/translate/baidu.ts`](https://github.com/zyronon/TypeWords/blob/main/app/libs/translate/baidu.ts) and instantiate with credentials
- **Call `translate()`** with text, source language, and target language parameters
- **Handle results** via the standardized `TranslateQueryResult` interface
- **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](https://fanyi-api.baidu.com/), 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.