Authentication overview

Typesense secures access to its search clusters using API keys. These keys are fundamental for authenticating requests made to the Typesense API, ensuring that only authorized applications and users can interact with your data. The system employs a straightforward, token-based authentication model, where a secret API key must be included with every request to verify identity and permissions. This approach is common in API design, providing a balance between security and ease of implementation for developers as described in RFC 6750 for bearer tokens.

Typesense differentiates between two primary types of API keys, each designed for specific access levels:

  • Admin API Key: This key grants full read and write access to your Typesense cluster. It can be used to perform all operations, including creating, updating, and deleting collections, documents, and other cluster configurations. Due to its extensive privileges, the Admin API Key should be treated with the highest level of confidentiality and used only in secure, server-side environments.
  • Search API Key: This key provides read-only access, specifically for search operations. It can be safely embedded in client-side applications (e.g., web browsers, mobile apps) as it cannot be used to modify or delete data. This segregation of duties is a critical security practice, minimizing the impact of a compromised client-side key.

All communication with Typesense clusters, whether self-hosted or Typesense Cloud, is expected to occur over HTTPS/TLS. This ensures that API keys and data transmitted between your application and the Typesense server are encrypted, protecting against eavesdropping and tampering as detailed in TLS security protocols.

Supported authentication methods

Typesense primarily supports API key authentication. This method is integrated across all client libraries and direct HTTP API calls. The design prioritizes simplicity and performance, aligning with Typesense's core objective as a fast, open-source search engine. While advanced authentication schemes like OAuth 2.0 or OpenID Connect are not directly built into Typesense's core API key mechanism, they can be implemented at an application layer upstream from Typesense to manage user identity and then issue appropriate Typesense search API keys.

API Key Authentication Details

When making an API request to Typesense, the API key is typically sent in the X-Typesense-API-Key HTTP header. This standard practice for API key authentication provides a clear and consistent way to secure requests across different programming languages and HTTP clients.

The following table summarizes the key types and their appropriate use cases:

Method When to Use Security Level
Admin API Key Server-side operations (indexing, configuration, CRUD on collections/documents), backend services. High (Full read/write access). Requires strict access control and secure storage.
Search API Key Client-side applications (web browsers, mobile apps), read-only search queries. Medium (Read-only access). Can be exposed client-side with minimal risk to data integrity.

Getting your credentials

The process for obtaining Typesense API keys varies slightly depending on whether you are using Typesense Cloud or a self-hosted instance.

Typesense Cloud

  1. Sign up or Log in: Access the Typesense Cloud dashboard by signing up for an account or logging in at Typesense Cloud.
  2. Cluster Creation: If you don't have a cluster, create one. During cluster creation, or by selecting an existing cluster, you will be directed to its details page.
  3. API Key Generation: On your cluster's dashboard, navigate to the 'API Keys' section. Typesense Cloud automatically generates an Admin API Key and a Search API Key for each cluster.
  4. Retrieve Keys: Copy these keys. For security reasons, the Admin API Key is typically shown only once upon creation or regeneration. It is crucial to store it securely immediately. Search API keys can generally be viewed at any time.

Self-Hosted Typesense

When running a self-hosted Typesense instance, you configure the API keys directly in the Typesense server's configuration. This is typically done upon starting the Typesense server.

  1. Configuration File: Keys are specified using command-line arguments or within a configuration file (e.g., typesense-server.ini or config.json).
  2. Admin API Key: Set the --api-key parameter (or api-key in config) to your desired Admin API Key value. This is a crucial step as it defines the primary key for administrative access. Example from the Typesense API Keys documentation: --api-key=xyz.
  3. Search API Key (Read-Only API Keys): To create read-only API keys, you typically use the Admin API Key to make a specific API call. This allows you to generate multiple read-only keys with different scopes and expiration times. For instance, you can define a key that only allows searching specific collections or filters. Example using curl with your Admin API Key to create a new search key:
    curl -X POST \n  'http://localhost:8108/keys' \n  -H 'Content-Type: application/json' \n  -H 'X-Typesense-API-Key: YOUR_ADMIN_API_KEY' \n  -d '{ \n    "description": "Search-only key for products collection", \n    "actions": ["documents:search"], \n    "collections": ["products"], \n    "expires_at": 1735689600 \n  }'
    This command creates a read-only key that can only search documents within the products collection. The expires_at field supports Unix timestamps for key expiry, adding another layer of security by limiting the key's validity period as specified in Typesense's API Keys documentation.

Authenticated request example

Authenticating a request to Typesense involves including the appropriate API key in the X-Typesense-API-Key HTTP header. Below are examples using curl for direct HTTP requests and a JavaScript SDK example, demonstrating how to set up authentication.

cURL Example (using Admin API Key)

This example demonstrates adding a document to a collection using an Admin API Key. Replace YOUR_TYPESENSE_ADMIN_API_KEY, YOUR_TYPESENSE_HOST, and YOUR_TYPESENSE_PORT with your actual cluster details.

curl -X POST \n  'https://YOUR_TYPESENSE_HOST:YOUR_TYPESENSE_PORT/collections/products/documents' \n  -H 'Content-Type: application/json' \n  -H 'X-Typesense-API-Key: YOUR_TYPESENSE_ADMIN_API_KEY' \n  -d '{ \n    "id": "124", \n    "name": "Smartwatch Pro", \n    "brand": "TechGear", \n    "price": 299.99 \n  }'

JavaScript SDK Example (using Search API Key)

When initializing the Typesense client in a client-side application, you provide the Search API Key. This example configures the client to perform search operations.

import Typesense from 'typesense' \n \nconst typesenseClient = new Typesense.Client({ \n  'nodes': [{ \n    'host': 'YOUR_TYPESENSE_HOST', \n    'port': 'YOUR_TYPESENSE_PORT', \n    'protocol': 'https' \n  }], \n  'apiKey': 'YOUR_TYPESENSE_SEARCH_API_KEY', // This is your Search API Key \n  'connectionTimeoutSeconds': 2 \n}) \n \n// Example search operation \ntypesenseClient.collections('products').documents().search({ \n  q: 'smartwatch', \n  query_by: 'name' \n}) \n.then(function (searchResults) { \n  console.log(searchResults) \n})

This JavaScript example illustrates how the apiKey parameter is used during client initialization. For more examples across different SDKs (Python, Ruby, PHP, Go, Dart, Java), refer to the Typesense API Reference.

Security best practices

Securing your Typesense cluster involves more than just generating API keys. Adhering to established security practices is crucial to protect your data and maintain the integrity of your search service.

1. API Key Management

  • Never commit API keys to version control: API keys, especially Admin API Keys, should never be directly embedded in your source code or committed to public or private repositories. Use environment variables, secret management services, or secure configuration files. Tools like dotenv (for local development) or cloud secret managers (e.g., AWS Secrets Manager, Google Secret Manager) are recommended for secure secret management.
  • Rotate API keys regularly: Periodically change your API keys, especially the Admin API Key. This minimizes the window of opportunity for an attacker if a key is compromised.
  • Use least privilege principle: Only generate and use API keys with the minimum necessary permissions. For client-side applications, always use Search API Keys. If you need a more granular read-only key, generate one with specific collection and action scopes.
  • Secure storage: Store Admin API Keys in secure, encrypted environments, accessible only by authorized personnel and applications.

2. Network Security

  • HTTPS/TLS everywhere: Ensure all communication with your Typesense cluster uses HTTPS. Typesense Cloud enforces this by default. For self-hosted instances, configure your server with a valid TLS certificate.
  • Firewall rules: Restrict access to your Typesense cluster's port (default 8108) using firewall rules. Only allow traffic from trusted IP addresses or networks where your applications are hosted.
  • Private networking: If possible, deploy your Typesense cluster and application within the same private network (e.g., VPC on AWS, VNet on Azure) to minimize exposure to the public internet.

3. Application-Level Security

  • Input validation: Sanitize and validate all user inputs before sending them to Typesense API to prevent injection attacks or unexpected behavior.
  • Rate limiting: Implement rate limiting on your application's endpoints that interact with Typesense, especially for search queries, to prevent abuse or denial-of-service attacks.
  • Error handling: Implement robust error handling. Avoid exposing sensitive information (like internal server errors or API keys) in error messages returned to clients.

4. Monitoring and Auditing

  • Monitor access logs: Regularly review Typesense server logs for unusual access patterns or failed authentication attempts.
  • Audit API key usage: For self-hosted instances, consider logging API key usage to track who is performing what actions. Typesense Cloud may offer similar monitoring capabilities.