Skip to main content

Overview

TalkifAI supports two authentication methods:
  1. Session-based authentication — For Studio UI and logged-in users (via Better Auth)
  2. API keys — For server-to-server API access
The authentication method you use depends on your use case:
Use CaseAuthentication Method
Studio UI (logged-in users)Session-based
Marketing site → Studio APIAPI key (x-api-key)
External backend → Studio APIAPI key (x-api-key)
Backend service (your own)Session-based or API key

Session-Based Authentication

For applications where users log in to TalkifAI Studio, authentication is handled automatically via Better Auth session cookies.

How It Works

  1. User logs in via TalkifAI Studio
  2. Session cookie is set automatically
  3. All API requests include the session cookie
  4. Backend validates session via auth.api.getSession()

Example (Server-Side)

import { auth } from "@/src/lib/auth";
import { headers } from "next/headers";

export async function GET() {
  const session = await auth.api.getSession({
    headers: await headers()
  });

  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // User is authenticated
  console.log("User:", session.user.email);
  console.log("Organization:", session.session.activeOrganizationId);
}

Example (Client-Side)

import { authClient } from "@/src/lib/auth-client";

function MyComponent() {
  const { data: session } = authClient.useSession();

  if (!session) {
    return <div>Please log in</div>;
  }

  return (
    <div>
      <p>Welcome, {session.user.name}!</p>
      <p>Organization: {session.session.activeOrganizationId}</p>
    </div>
  );
}

API Key Authentication

For server-to-server communication (e.g., marketing site → Studio API, external backends), use API keys.

Generating an API Key (Via Studio UI)

Navigation: Studio → Organization → API Keys URL: /organization/api-key
Owner access required: Only organization owners can generate API keys. Admins and Members cannot access this feature.
Step-by-Step Process:
  1. Navigate to API Keys Page
    • Go to Studio → Organization (sidebar)
    • Click API Keys in the organization settings
  2. Enter Key Details
    • Key Name (required, max 50 characters)
      • Example: “Production Server”, “Marketing Site”, “Dev Testing”
    • Organization is automatically selected from your active session
  3. Click “Generate API Key”
    • Button shows loading spinner while processing
    • Backend creates key via Better Auth
  4. Copy the Key Immediately ⚠️
    • The full key is shown only once in a dark gray box
    • Click Copy button to copy to clipboard
    • Shows “Copied!” confirmation for 2 seconds
    • Important: You cannot view the key again after leaving the page
  5. Key Details Shown
    • Created date
    • Expires date (1 year from creation)
    • API endpoints that accept this key:
      • Public Chat API: https://api.talkifai.dev/v1/chat
      • Data Export API: https://api.talkifai.dev/api/export
Security Warning: API keys grant full access to your organization.
  • ✅ Copy the key immediately and store in a password manager
  • ✅ Use environment variables in your application
  • ❌ Never commit to version control (add to .gitignore)
  • ❌ Never expose in client-side code
  • ❌ Never share via email or chat
After Generation:
  • Key appears in the “Existing Keys” list on the right
  • Shows: Name, prefix (e.g., abc123••••••••), created date, expires date, status
  • Can be revoked anytime by clicking Delete (trash icon)

API Key Format

TalkifAI API keys are random strings (no special prefix like tk_live_). Example: abc123def456... (64 characters)

Using API Keys

Include the API key in the x-api-key header:
curl https://api.talkifai.dev/api/agents \
  -H "x-api-key: your_api_key_here"
// JavaScript example
const response = await fetch('https://api.talkifai.dev/api/agents', {
  headers: {
    'x-api-key': process.env.TALKIFAI_API_KEY,
    'Content-Type': 'application/json'
  }
});

const data = await response.json();
# Python example
import httpx

headers = {
    "x-api-key": os.environ["TALKIFAI_API_KEY"],
    "Content-Type": "application/json"
}

response = httpx.get(
    "https://api.talkifai.dev/api/agents",
    headers=headers
)

API Key Features

FeatureDescription
Organization-scopedKeys are tied to a specific organization
Rate limiting1000 requests per hour (default)
Expiration1 year from creation (default)
MetadataStores creator, creation date, org ID

Organization Context

All API operations are scoped to your active organization.

Session-Based (Studio Users)

The active organization is stored in the session:
const session = await auth.api.getSession({ headers });

if (session) {
  const orgId = session.session.activeOrganizationId;
  console.log("Active org:", orgId);
}
Users can switch organizations in the Studio UI, which updates activeOrganizationId.

API Key Authentication

API keys are automatically scoped to the organization they were created in:
// When creating an API key
const apiKeyData = await auth.api.createApiKey({
  body: {
    name: "Production Backend",
    userId: session.user.id,
    metadata: {
      organizationId: "org_abc123",  // Key is scoped to this org
    }
  }
});
All requests with this key automatically operate within that organization.

Environment Variables

Store credentials securely as environment variables:
# .env.local (development)
# .env.production (production)

# API Key (for server-to-server)
TALKIFAI_API_KEY=your_api_key_here

# Base URL
TALKIFAI_BASE_URL=https://api.talkifai.dev
Never commit .env files to version control. Add them to .gitignore:
# .gitignore
.env
.env.local
.env.production

Verifying Your API Key

Test your API key with a simple request:
curl https://api.talkifai.dev/api/agents \
  -H "x-api-key: $TALKIFAI_API_KEY"
Success Response:
{
  "agents": [
    {
      "id": "agent_abc123",
      "name": "Customer Support Bot",
      "description": "Handles customer inquiries"
    }
  ]
}
Error Response (Invalid Key):
{
  "error": "Unauthorized - Invalid or missing API key"
}

Revoking API Keys

To revoke a key:
  1. Go to Studio → Organization → API Keys
  2. Find the key in the “Existing Keys” list (right column)
  3. Click Delete (trash icon with red button)
  4. Confirm deletion in the dialog: “Are you sure you want to delete this API key?”
Revoked keys immediately return 401 Unauthorized on all requests.
Irreversible Action: Once revoked, the key cannot be recovered. You’ll need to generate a new key and update your applications.

Security Best Practices

Rotate Keys Regularly

Generate new API keys every 90 days. Delete old keys after rotation.

Use Separate Keys

Use different keys for development, staging, and production environments.

Monitor Active Keys

Check Organization → API Keys regularly. Revoke unused keys immediately.

Never Log Keys

Never log API keys in application logs. Redact sensitive headers.

Use Environment Variables

Store keys in environment variables, not in code or config files.

Limit Key Permissions

Create separate keys for different services with minimal required access.

Error Codes

StatusErrorDescription
401UnauthorizedMissing or invalid API key / session
401Invalid API keyAPI key is malformed or revoked
403ForbiddenValid auth but insufficient permissions
403Not a member of the selected organizationUser/org mismatch
429Rate limit exceededToo many requests (API keys only)