npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@techify/next-translate

v1.0.1

Published

A powerful translation library for Next.js with automatic IP-based language detection and Babel plugin for automatic string wrapping

Readme

@techify/next-translate

A powerful, type-safe translation library for Next.js applications with automatic IP-based language detection and a Babel plugin for seamless text transformation.

npm version License: MIT TypeScript

Features

  • 🌍 Automatic Language Detection - Detects user language from IP address and browser preferences
  • 🔄 React Context API - Provides translation state to all components via React Context
  • 📝 Text Component - Simple <Text> component for translatable content
  • 🔌 Babel Plugin - Automatically wraps JSX text in <Text> components
  • 🎯 TypeScript First - Full TypeScript support with comprehensive types
  • Next.js Optimized - Built specifically for Next.js App Router
  • 🚀 Edge Runtime Compatible - Works with Next.js middleware and Edge functions
  • 📦 Zero Configuration - Works out of the box with sensible defaults

Supported Languages

Currently supports:

  • 🇺🇸 English (en)
  • 🇧🇷 Portuguese (pt)

Installation

npm install @techify/next-translate
# or
yarn add @techify/next-translate
# or
pnpm add @techify/next-translate

Quick Start

1. Wrap Your Layout

In your root layout (app/layout.tsx), wrap your application with the <NextTranslate> component:

// app/layout.tsx
import { NextTranslate } from '@techify/next-translate';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <NextTranslate>
          {children}
        </NextTranslate>
      </body>
    </html>
  );
}

2. Use the Text Component

Use the <Text> component to make text translatable:

// app/page.tsx
import { Text } from '@techify/next-translate';

export default function HomePage() {
  return (
    <main>
      <h1><Text>Welcome</Text></h1>
      <p><Text>Thank you for visiting our website</Text></p>
      <button><Text>Get started today</Text></button>
    </main>
  );
}

3. (Optional) Set Up Babel Plugin

For automatic text transformation, run the setup script:

npx next-translate-setup

This will configure Babel to automatically wrap JSX text in <Text> components, so you can write:

// Before Babel transformation
<div>Hello World</div>

// After Babel transformation (automatic)
<div><Text>Hello World</Text></div>

API Reference

Components

<NextTranslate>

The main wrapper component that provides translation context.

interface NextTranslateProps {
  children: React.ReactNode;
  defaultLanguage?: 'pt' | 'en';        // Default: 'en'
  customTranslations?: Translations;     // Custom translations to merge
  disableAutoDetect?: boolean;           // Disable IP detection
  forceLanguage?: 'pt' | 'en';          // Force a specific language
}

Example with options:

<NextTranslate 
  defaultLanguage="pt"
  customTranslations={{
    pt: { 'My Custom Text': 'Meu Texto Personalizado' },
    en: { 'My Custom Text': 'My Custom Text' }
  }}
>
  {children}
</NextTranslate>

<Text>

Renders translated text based on the current language.

interface TextProps {
  children: string;                      // Text to translate
  className?: string;                    // CSS class
  style?: React.CSSProperties;           // Inline styles
  as?: 'span' | 'div' | 'p' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'strong' | 'em' | 'label' | 'a' | 'button';
  skipTranslation?: boolean;             // Skip translation for this text
}

Examples:

// Basic usage
<Text>Hello</Text>

// With custom tag
<Text as="h1">Welcome</Text>

// With styling
<Text className="text-lg font-bold" style={{ color: 'blue' }}>
  Thank you
</Text>

// Skip translation (for brand names, etc.)
<Text skipTranslation>Techify™</Text>

<T> (Alias)

Shorter alias for the <Text> component:

import { T } from '@techify/next-translate';

<T>Hello</T>

Hooks

useTranslate()

Access the full translation context.

import { useTranslate } from '@techify/next-translate';

function MyComponent() {
  const { language, setLanguage, translate, isReady } = useTranslate();
  
  return (
    <div>
      <p>Current language: {language}</p>
      <p>{translate('Hello')}</p>
      <button onClick={() => setLanguage('pt')}>Português</button>
      <button onClick={() => setLanguage('en')}>English</button>
    </div>
  );
}

useLanguage()

Simple hook for language management.

import { useLanguage } from '@techify/next-translate';

function LanguageSwitcher() {
  const { language, setLanguage, toggleLanguage, isLanguage } = useLanguage();
  
  return (
    <button onClick={toggleLanguage}>
      {isLanguage('pt') ? '🇧🇷 PT' : '🇺🇸 EN'}
    </button>
  );
}

useT()

Get a translation function for inline use.

import { useT } from '@techify/next-translate';

function SearchBox() {
  const t = useT();
  
  return (
    <input 
      placeholder={t('Search')} 
      aria-label={t('Search')}
    />
  );
}

Higher-Order Component

withTranslation()

Create a pre-configured translated text component.

import { withTranslation } from '@techify/next-translate';

const WelcomeMessage = withTranslation('Welcome to our website', {
  as: 'h1',
  className: 'hero-title'
});

// Usage
<WelcomeMessage />

Server-Side Utilities

detectLanguageFromRequest()

Detect language from a request object (for middleware or server components).

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { detectLanguageFromRequest } from '@techify/next-translate';

export function middleware(request: NextRequest) {
  const language = detectLanguageFromRequest(request);
  
  // You can use this to redirect or set cookies
  const response = NextResponse.next();
  response.cookies.set('language', language);
  
  return response;
}

NextTranslateServer

Server component wrapper for when you know the language at build/request time.

import { NextTranslateServer } from '@techify/next-translate';

export default async function Layout({ children }) {
  // Get language from cookies, headers, or database
  const language = 'pt';
  
  return (
    <NextTranslateServer language={language}>
      {children}
    </NextTranslateServer>
  );
}

IP Detection Utilities

For advanced use cases, you can access the IP detection utilities directly:

import {
  detectLanguageFromIP,
  extractClientIP,
  getLanguageFromHeaders,
} from '@techify/next-translate';

// Detect language from IP
const result = detectLanguageFromIP('189.40.100.1');
console.log(result.language); // 'pt'
console.log(result.country);  // 'BR'

// Extract client IP from headers
const ip = extractClientIP(request.headers);

// Get language from request headers
const language = getLanguageFromHeaders(request.headers);

Babel Plugin

The Babel plugin automatically wraps JSX text content with <Text> components.

Setup

Run the setup script to configure Babel:

npx next-translate-setup

Or manually add to your babel.config.js:

module.exports = {
  presets: ['next/babel'],
  plugins: ['@techify/next-translate/babel-plugin'],
};

Options

module.exports = {
  presets: ['next/babel'],
  plugins: [
    ['@techify/next-translate/babel-plugin', {
      // Tags to exclude from transformation
      excludeTags: ['script', 'style', 'code', 'pre', 'Text', 'T'],
      
      // Attributes to exclude from transformation
      excludeAttributes: ['className', 'id', 'href', 'src'],
      
      // Minimum text length to transform
      minTextLength: 1,
    }],
  ],
};

What Gets Transformed

Will be transformed:

<div>Hello World</div>
// → <div><Text>Hello World</Text></div>

<p>Welcome to our website</p>
// → <p><Text>Welcome to our website</Text></p>

Will NOT be transformed:

// Already wrapped
<Text>Hello</Text>

// Excluded tags
<code>npm install</code>

// Numbers only
<span>123</span>

// URLs
<a href="https://example.com">https://example.com</a>

// Empty or whitespace
<div>   </div>

Custom Translations

You can add custom translations by passing them to <NextTranslate>:

const myTranslations = {
  pt: {
    'My App Name': 'Nome do Meu App',
    'Custom greeting': 'Saudação personalizada',
  },
  en: {
    'My App Name': 'My App Name',
    'Custom greeting': 'Custom greeting',
  },
};

<NextTranslate customTranslations={myTranslations}>
  {children}
</NextTranslate>

Built-in Translations

The library comes with 100+ common phrases pre-translated. See the full list in translations.json.

Some examples:

  • Hello / Olá
  • Welcome / Bem-vindo
  • Thank you / Obrigado
  • Login / Entrar
  • Settings / Configurações
  • Add to cart / Adicionar ao carrinho
  • And many more...

TypeScript Support

The library is written in TypeScript and exports all types:

import type {
  Language,
  TranslationDictionary,
  Translations,
  TranslateContextValue,
  NextTranslateProps,
  TextProps,
} from '@techify/next-translate';

Edge Runtime Support

The library is compatible with Next.js Edge Runtime:

// app/api/route.ts
export const runtime = 'edge';

import { detectLanguageFromRequest } from '@techify/next-translate';

export async function GET(request: Request) {
  const language = detectLanguageFromRequest(request as any);
  
  return Response.json({ language });
}

Examples

Language Switcher Component

'use client';

import { useLanguage } from '@techify/next-translate';

export function LanguageSwitcher() {
  const { language, setLanguage } = useLanguage();
  
  return (
    <div className="flex gap-2">
      <button
        onClick={() => setLanguage('en')}
        className={language === 'en' ? 'font-bold' : ''}
      >
        🇺🇸 English
      </button>
      <button
        onClick={() => setLanguage('pt')}
        className={language === 'pt' ? 'font-bold' : ''}
      >
        🇧🇷 Português
      </button>
    </div>
  );
}

Complete Page Example

// app/page.tsx
import { Text, T } from '@techify/next-translate';
import { LanguageSwitcher } from './LanguageSwitcher';

export default function HomePage() {
  return (
    <main className="container mx-auto p-4">
      <header className="flex justify-between items-center mb-8">
        <h1><Text as="span">Welcome</Text></h1>
        <LanguageSwitcher />
      </header>
      
      <section className="mb-8">
        <T as="h2">About</T>
        <T as="p">Welcome to our website</T>
      </section>
      
      <section>
        <T as="h2">Contact</T>
        <T as="p">Contact us</T>
        <button className="btn">
          <T>Send message</T>
        </button>
      </section>
    </main>
  );
}

Using with Forms

'use client';

import { useT } from '@techify/next-translate';

export function ContactForm() {
  const t = useT();
  
  return (
    <form>
      <label>
        {t('Email')}
        <input 
          type="email" 
          placeholder={t('Enter your email')} 
        />
      </label>
      
      <label>
        {t('Password')}
        <input 
          type="password" 
          placeholder={t('Password')} 
        />
      </label>
      
      <button type="submit">
        {t('Submit')}
      </button>
    </form>
  );
}

Troubleshooting

Text not translating

  1. Make sure your component is wrapped with <NextTranslate>
  2. Check if the text exists in translations.json
  3. Verify you're using the <Text> component

Language not detected

  1. IP-based detection works only in production with real IPs
  2. In development, it falls back to browser language
  3. Use forceLanguage prop for testing

Babel plugin not working

  1. Make sure you ran npx next-translate-setup
  2. Restart your development server
  3. Clear the .next cache folder

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting a pull request.

License

MIT © Techify


Made with ❤️ by Techify