Authentication overview

LibreTranslate offers distinct authentication mechanisms depending on whether you are using their hosted cloud service or a self-hosted instance. The hosted service, including its free tier, mandates the use of an API key to control access, manage usage quotas, and secure translation requests. This key serves as a unique identifier for your application and helps track character consumption.

For self-hosted deployments, LibreTranslate provides greater flexibility. By default, a locally run instance might not require any authentication, making it suitable for private networks or internal applications where network-level security is already in place. However, for instances exposed to the internet or shared environments, administrators are responsible for implementing appropriate security measures, which can include custom token validation, reverse proxy authentication, or integrating with existing identity providers. The choice of method for self-hosted instances depends on the deployment environment's security requirements and existing infrastructure. The official LibreTranslate documentation provides guidance on these configurations for self-hosted options.

Supported authentication methods

LibreTranslate's authentication methods vary based on the deployment model. The primary method for the cloud service is API key authentication, while self-hosted instances offer more customizable options.

LibreTranslate Authentication Methods
Method When to Use Security Level
API Key (Cloud Service) Accessing LibreTranslate's hosted API, including free and paid tiers. Standard. Requires secure handling of the key.
No Authentication (Self-Hosted) Private networks where the LibreTranslate instance is not publicly accessible. Low (relies on network isolation).
Custom Token/Header (Self-Hosted) When a basic access control layer is needed for self-hosted instances. Implemented via server-side configuration. Variable (depends on token strength and implementation).
Reverse Proxy Authentication (Self-Hosted) Adding a robust authentication layer (e.g., OAuth2, JWT validation) in front of a self-hosted LibreTranslate instance using tools like Nginx, Caddy, or Kong. High (leveraging established proxy security features).

The self-hosted solution's flexibility allows developers to integrate LibreTranslate into existing security infrastructures. For example, a common practice for publicly accessible self-hosted instances is to deploy a reverse proxy like Nginx or Caddy. These proxies can then handle authentication, such as basic auth, client certificate authentication, or integration with an OAuth 2.0 provider, before forwarding requests to the LibreTranslate backend. This offloads the authentication burden from the translation service itself and allows for more sophisticated security policies. The IETF's RFC 6749 details the OAuth 2.0 Authorization Framework, which is commonly implemented by reverse proxies.

Getting your credentials

For LibreTranslate Cloud Service

  1. Sign Up/Log In: Navigate to the LibreTranslate homepage and sign up for a new account or log in to an existing one.
  2. Access Dashboard: Once logged in, you will typically be redirected to your user dashboard or account settings page.
  3. Locate API Keys Section: Look for a section explicitly labeled "API Keys," "Developer Settings," or similar.
  4. Generate Key: If you don't have an API key already, there will be an option to generate a new one. Follow the prompts, which may include naming your key for organizational purposes.
  5. Securely Store Key: Once generated, your API key will be displayed. Copy this key immediately and store it securely. LibreTranslate typically only shows the key once for security reasons. For information on managing your subscription and API usage, refer to the LibreTranslate pricing page.

For Self-Hosted LibreTranslate

For self-hosted instances, credential setup is managed during the deployment and configuration phase. By default, a self-hosted instance may not have any authentication configured. To add authentication:

  1. Review Deployment Options: Consult the LibreTranslate documentation for self-hosting, which covers various deployment methods (e.g., Docker, direct installation).
  2. Configure Authentication in config.json: Many self-hosted applications, including LibreTranslate, allow configuration of security settings through a config.json or environment variables. You might be able to define custom tokens or enable specific authentication middleware.
  3. Implement Reverse Proxy: For robust authentication, set up a reverse proxy (e.g., Nginx, Apache HTTP Server) in front of your LibreTranslate instance. Configure the proxy to handle authentication (e.g., basic authentication, OAuth 2.0 tokens, JWT validation) before forwarding requests to LibreTranslate. The Cloudflare developer documentation on OAuth applications provides examples of how proxies can integrate with identity providers.
  4. Manage Access Control: If using custom tokens or an internal system, implement your own access control logic to generate, validate, and revoke these tokens.

Authenticated request example

This example demonstrates how to make an authenticated translation request to the LibreTranslate cloud API using Python and the requests library, incorporating an API key.

import requests
import os

# It's best practice to store your API key in an environment variable
API_KEY = os.getenv('LIBRETRANSLATE_API_KEY')

if not API_KEY:
    raise ValueError("LIBRETRANSLATE_API_KEY environment variable not set.")

# LibreTranslate Cloud API endpoint
BASE_URL = "https://libretranslate.com/translate"

headers = {
    "Content-Type": "application/json",
    "X-API-Key": API_KEY # The API key is sent in the X-API-Key header
}

data = {
    "q": "Hello, world!",
    "source": "en",
    "target": "es",
    "format": "text"
}

try:
    response = requests.post(BASE_URL, headers=headers, json=data)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    translation_result = response.json()
    print(f"Translated text: {translation_result['translatedText']}")
except requests.exceptions.HTTPError as errh:
    print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"Something Else: {err}")

In this example, the API key is passed in the X-API-Key HTTP header. This is the standard method for authenticating with the LibreTranslate cloud service. Always retrieve your API key from environment variables or a secure configuration management system rather than hardcoding it directly into your application code.

For self-hosted instances with custom token authentication, the header name or parameter might differ based on your specific configuration. For example, you might configure your server to accept a token in an Authorization: Bearer <token> header, following common OAuth 2.0 patterns, or a custom header like X-Custom-Auth-Token.

Security best practices

Securing your LibreTranslate integration, whether cloud-based or self-hosted, involves several key practices:

  • API Key Management (Cloud Service):
    • Environment Variables: Store your LibreTranslate API key as an environment variable (e.g., LIBRETRANSLATE_API_KEY) rather than hardcoding it in your source code. This prevents accidental exposure in version control systems.
    • Access Control: Restrict access to API keys within your team or organization using appropriate access control policies.
    • Rotation: Regularly rotate your API keys, especially if you suspect a compromise or as part of a routine security policy.
    • Least Privilege: If LibreTranslate offered fine-grained permissions (which it currently does not for API keys), you would grant only the necessary permissions to each key.
  • HTTPS/TLS Encryption:
    • Always ensure all communication with the LibreTranslate API (cloud or self-hosted) occurs over HTTPS (HTTP Secure). This encrypts data in transit, protecting your API key and translated text from eavesdropping. The LibreTranslate cloud service enforces HTTPS by default.
    • For self-hosted instances, configure your web server or reverse proxy to use valid TLS certificates and redirect all HTTP traffic to HTTPS. Let's Encrypt offers free, automated, and open certificates with Certbot for securing self-hosted services.
  • Input Validation and Sanitization:
    • Although not strictly an authentication concern, validating and sanitizing input before sending it to the LibreTranslate API is crucial for overall application security. This prevents potential injection attacks or unexpected behavior.
  • Rate Limiting:
    • Implement client-side rate limiting in your application to prevent abuse or accidental excessive calls to the API. The LibreTranslate cloud service has its own rate limits, but client-side limits add an additional layer of control.
    • For self-hosted instances, configure rate limiting on your reverse proxy or within the LibreTranslate application's settings if available, to protect against denial-of-service attacks.
  • Error Handling:
    • Implement robust error handling for API requests. Avoid exposing sensitive information (like API keys or internal server details) in error messages returned to clients.
  • Regular Updates (Self-Hosted):
    • Keep your self-hosted LibreTranslate instance and its underlying dependencies (operating system, Python, Docker) updated to the latest stable versions. This ensures you benefit from the latest security patches and bug fixes.