Skip to main content

Auth Integration (2 Minutes)

Quick guide: Integrate Cortex with your existing authentication system.

The Simple Truth

Cortex works with whatever auth system you already use. No special integration, no proprietary protocol, no heavy lifting.

Your auth system → Extract userIdPass to Cortex → Done.

3-Line Integration

auth-setup.tstypescript
1import { Cortex, createAuthContext } from "@cortexmemory/sdk";
2
3// 1. Extract from YOUR existing auth (any system)
4const auth = createAuthContext({
5userId: yourUser.id, // Required
6tenantId: yourUser.tenantId, // Optional (for SaaS)
7});
8
9// 2. Pass to Cortex
10const cortex = new Cortex({
11convexUrl: process.env.CONVEX_URL!,
12auth,
13});
14
15// 3. Use normally - userId auto-injected
16await cortex.memory.remember({
17memorySpaceId: "user-space",
18userMessage: "Hello",
19agentResponse: "Hi!",
20userName: yourUser.name,
21// userId automatically set from auth
22});
That's it!

No SDKs to install, no webhooks to configure, no middleware to debug.

Supported Auth Providers

Info

Cortex is framework-agnostic — it works with any auth system that provides a user ID.

Clerk, Auth0, NextAuth, Supabase Auth, Firebase Auth, Okta, WorkOS, Custom JWT — any system that provides a user ID.

Provider Setup

1

Install Clerk SDK

Terminal
$ npm install @clerk/nextjs
2

Configure Cortex with Clerk

import { Cortex, createAuthContext } from '@cortexmemory/sdk';
import { auth } from '@clerk/nextjs';

export async function getCortexClient() {
const { userId, orgId } = auth();

if (!userId) {
throw new Error('Not authenticated');
}

return new Cortex({
convexUrl: process.env.CONVEX_URL!,
auth: createAuthContext({
userId,
tenantId: orgId, // For multi-tenant apps
authProvider: 'clerk',
authMethod: 'oauth',
authenticatedAt: Date.now(),
}),
});
}

The pattern is always the same — just map your auth data to Cortex's simple structure.

AuthContext Reference

ParameterTypeRequiredDefaultDescription
userIdstringYesUnique user identifier from your auth system
tenantIdstringNoOrganization/tenant ID for multi-tenant apps
sessionIdstringNoCurrent session identifier
authMethodstringNoName of auth provider (for analytics)
authenticatedAtnumberNoTimestamp of authentication (Unix ms)

Multi-Tenancy Support

SaaS Applications

For multi-tenant SaaS apps, always include tenantId in your auth context. This ensures complete data isolation between customers.

const cortex = new Cortex({
convexUrl: process.env.CONVEX_URL!,
auth: createAuthContext({
userId: 'user-123',
tenantId: 'customer-acme', // Critical for SaaS!
authProvider: 'clerk',
authMethod: 'oauth',
}),
});

// All operations are now scoped to customer-acme
await cortex.memory.remember({...}); // tenantId auto-injected

See Isolation Boundaries for the complete multi-tenancy guide.

What Happens Behind the Scenes

1

Auto-Injection

userId and tenantId are automatically added to all operations:

// You write:
await cortex.memory.remember({ memorySpaceId: "space-1", ... });

// SDK automatically does:
await cortex.memory.remember({
memorySpaceId: "space-1",
userId: "user-123", // ← From auth
tenantId: "tenant-abc", // ← From auth
...
});
2

Auto-Filtering

All queries are automatically filtered by tenantId:

// You write:
const memories = await cortex.memory.search("space-1", "query");

// SDK automatically filters:
// WHERE memorySpaceId = "space-1" AND tenantId = "tenant-abc"
3

Enables Features

Auth context enables: GDPR cascade deletion by userId, multi-tenant data isolation, session tracking, and audit trails.

Security Best Practices

Server-Side Only

Always create the Cortex client on the server side. Never expose your Convex URL or auth context to the client.

Never Trust Client Data

Always get the user ID from your auth system's server-side session, never from client-submitted data.

Common Patterns

// app/api/cortex/route.ts
import { Cortex, createAuthContext } from '@cortexmemory/sdk';
import { auth } from '@clerk/nextjs';

export async function POST(req: Request) {
const { userId, orgId } = auth();

const cortex = new Cortex({
convexUrl: process.env.CONVEX_URL!,
auth: createAuthContext({ userId, tenantId: orgId }),
});

// Use cortex...
}

Without Auth (For Testing)

Cortex works without auth context for development and testing:

// No auth - for prototypes/testing
const cortex = new Cortex({
convexUrl: process.env.CONVEX_URL!,
// No auth
});

// Works, but you must set userId manually
await cortex.memory.remember({
memorySpaceId: "test-space",
userId: "test-user", // Manual
userMessage: "Hello",
agentResponse: "Hi!",
userName: "Test User",
});
When No Auth is OK

Quick prototypes, development/testing, single-user apps, CLI tools.

When You Need Auth

Production APIs, multi-tenant SaaS, user-facing applications.

Common Questions

No! Cortex doesn't require any auth provider SDKs. Use whatever you already have.

Just update your extraction code. Cortex doesn't care where userId comes from.

No! Auth context is request-scoped. No async integrations needed.

Store in metadata field. Cortex provides data isolation, you handle authorization logic.

Yes! Use test values: createAuthContext({ userId: "test-user" })

Next Steps