Skip to content

lisenhuang/ai-translator-nextjs

Repository files navigation

AI Translator - Next.js Frontend

A beautiful, responsive AI translation interface built with Next.js 15, TypeScript, and shadcn/ui. Features Google Translate-like design with Cloudflare Turnstile integration, multi-language support, and dark/light theme switching.

🌐 Live Demo

Experience the AI Translator in action: https://translate.english-dictionary.app/

🎯 Try the live demo to see all features including multi-language support, dark/light themes, and seamless translation experience.

✨ Features

  • 🌐 Multi-language Support - Interface available in 10 languages with automatic system language detection
  • 🎨 Beautiful UI - Google Translate-inspired design with responsive layout
  • πŸŒ“ Theme Switching - Dark/light mode toggle with system preference detection
  • πŸ”’ Cloudflare Turnstile - Secure verification with pass-based authentication
  • πŸ“± Responsive Design - Optimized for desktop and mobile devices
  • ⚑ Auto-resize TextArea - Dynamic text input with character counting
  • πŸ“‹ Copy/Paste/Clear - Quick action buttons for better UX
  • πŸš€ Modern Stack - Next.js 15 App Router, TypeScript, Tailwind CSS

πŸ›  Tech Stack

  • Framework: Next.js 15 (App Router)
  • Language: TypeScript
  • Styling: Tailwind CSS v4
  • UI Components: shadcn/ui
  • Package Manager: pnpm
  • Theme: next-themes
  • Icons: Lucide React
  • Security: Cloudflare Turnstile

πŸ“‹ Prerequisites

  • Node.js 18+
  • pnpm (recommended) or npm/yarn
  • A running AI Translator backend API

πŸš€ Quick Start

1. Clone and Install

# Clone the repository
git clone [email protected]:chismo950/ai-translator-nextjs.git
cd ai-translator-nextjs-cursor

# Install dependencies
pnpm install

2. Configuration Setup

The application uses a centralized configuration system in src/lib/config.ts. Update the API base URL:

// src/lib/config.ts
export const API_CONFIG = {
  // Update this URL to your backend API
  BASE_URL: "https://your-api-domain.com",
  // ... other settings
} as const;

Key Configuration Options:

  • API_CONFIG.BASE_URL: Your backend API URL
    • Local development: http://localhost:8080
    • Production: Your deployed API URL
  • TRANSLATION_CONFIG.MAX_CHARACTERS: Character limit for translations
  • TRANSLATION_CONFIG.TEXTAREA: Text area rows configuration
  • TURNSTILE_CONFIG: Cloudflare Turnstile widget settings

3. Backend Requirements

Your backend API must provide these endpoints:

GET  /_turnstile/sitekey    # Returns Turnstile configuration
POST /v1/translate          # Translation endpoint

Expected API responses:

GET /_turnstile/sitekey:

{
  "siteKey": "your-turnstile-site-key",
  "headerName": "CF-Turnstile-Token"
}

POST /v1/translate:

{
  "sourceLang": "auto",
  "targetLang": "en",
  "translatedText": "Hello everyone!"
}

4. Run Development Server

# Start the development server
pnpm dev

# Or with npm
npm run dev

Open http://localhost:3000 in your browser.

πŸ”§ Configuration

Character Limits

Edit character limits in src/lib/config.ts:

export const TRANSLATION_CONFIG = {
  MAX_CHARACTERS: 5000, // Hard limit
  SOFT_LIMIT: 4000, // Warning threshold
  TEXTAREA: {
    MIN_ROWS: 4,
    MAX_ROWS: 15,
  },
} as const;

Supported Languages

Add or modify languages in src/lib/i18n.ts:

export const languages: Record<SupportedLanguage, string> = {
  en: "English",
  zh: "δΈ­ζ–‡",
  // Add more languages...
};

Theme Configuration

Theme settings are in src/app/layout.tsx:

<ThemeProvider
  attribute="class"
  defaultTheme="system"  // 'light' | 'dark' | 'system'
  enableSystem
  disableTransitionOnChange
>

🎯 Usage

Basic Translation

  1. Select Languages: Choose source and target languages
  2. Enter Text: Type or paste text in the source textarea
  3. Verify: Complete Turnstile challenge if prompted
  4. Translate: Click the translate button
  5. Copy Result: Use the copy button to copy the translation

Features

  • Auto-detect: Source language can be set to "Detect language"
  • Swap Languages: Click the swap button to reverse source/target
  • Character Counter: Shows usage against limits
  • Responsive Design: Works on mobile and desktop
  • Theme Toggle: Switch between light/dark themes
  • Multi-language UI: Interface adapts to user's system language

Turnstile Flow

  1. First Use: Turnstile widget appears for verification
  2. Verification: User completes the challenge
  3. Pass Issued: Server provides a short-lived pass
  4. Subsequent Requests: Pass allows multiple translations
  5. Pass Expiry: Widget reappears when pass expires

πŸ— Project Structure

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ layout.tsx          # Root layout with providers
β”‚   β”œβ”€β”€ page.tsx            # Main page
β”‚   └── globals.css         # Global styles
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ ui/                 # shadcn/ui components
β”‚   β”œβ”€β”€ auto-resize-textarea.tsx
β”‚   β”œβ”€β”€ character-counter.tsx
β”‚   β”œβ”€β”€ header.tsx
β”‚   β”œβ”€β”€ language-selector.tsx
β”‚   β”œβ”€β”€ theme-provider.tsx
β”‚   β”œβ”€β”€ theme-toggle.tsx
β”‚   └── translator.tsx      # Main translation component
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ use-language.ts     # Language switching hook
β”‚   β”œβ”€β”€ use-toast.tsx       # Toast notifications
β”‚   └── useTurnstile.tsx    # Turnstile widget management
└── lib/
    β”œβ”€β”€ apiClient.ts        # API client with pass management
    β”œβ”€β”€ i18n.ts             # Internationalization
    └── utils.ts            # Utility functions

πŸš€ Production Deployment

Build for Production

# Create production build
pnpm build

# Start production server
pnpm start

Configuration for Production

Update src/lib/config.ts with your production settings:

export const API_CONFIG = {
  BASE_URL: "https://your-production-api.com",
  // ... other production settings
} as const;

Deployment Platforms

Vercel:

# Deploy to Vercel
npx vercel --prod

Example Deployment: See the live production deployment at https://translate.english-dictionary.app/ for reference.

Netlify:

# Build command
pnpm build

# Publish directory
out

Docker:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

πŸ”’ Security Considerations

  • Turnstile Keys: Keep your secret key on the backend only
  • API Endpoints: Ensure proper CORS configuration
  • Rate Limiting: Implement backend rate limiting
  • Pass Storage: Passes are stored in memory only (not localStorage)

πŸ› Troubleshooting

Common Issues

Turnstile not loading:

  • Check console for script loading errors
  • Verify site key configuration
  • Ensure proper CORS headers

Translation failures:

  • Verify API base URL in environment
  • Check backend CORS configuration
  • Ensure proper request headers

Theme not working:

  • Verify ThemeProvider wraps your app
  • Check CSS custom properties
  • Ensure suppressHydrationWarning is set

Debug Mode

Enable detailed logging by adding to your environment:

NODE_ENV=development

πŸ“š API Reference

Frontend API Client

import { postTranslate, getTurnstileSiteKey } from "@/lib/apiClient";

// Get Turnstile configuration
const config = await getTurnstileSiteKey();

// Translate text
const result = await postTranslate(
  {
    text: "Hello world",
    sourceLang: null, // auto-detect
    targetLang: "es",
  },
  {
    turnstileHeaderName: "CF-Turnstile-Token",
    getTurnstileToken: () => "turnstile-token",
  }
);

Hooks

// Language switching
const { currentLanguage, setCurrentLanguage, t } = useLanguage();

// Turnstile management
const { containerRef, render, refresh, token, isVerified } = useTurnstile();

// Toast notifications
const { toast } = useToast();

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

🌟 Demo & Examples

Live Demo

Check out the fully functional demo at https://translate.english-dictionary.app/ to experience:

  • Real-time Translation: Powered by advanced AI models
  • Multi-language Interface: Automatic system language detection
  • Responsive Design: Seamless experience across devices
  • Theme Switching: Dark/light mode with system preference
  • Cloudflare Turnstile: Security verification in action

This demo showcases all the features implemented in this repository and serves as a reference for successful deployment.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments