The lazy pattern lets Next.js build without opening a DB connection.
3
Wire the route handler
app/api/kavach/[...kavach]/route.ts
import { kavachNextjs } from '@kavachos/nextjs';import { getKavach } from '@/lib/kavach';const { GET, POST } = kavachNextjs(getKavach);export { GET, POST };
Pick a path that does not collide with your existing auth. /api/kavach/* lives next to /api/auth/* (Clerk / Auth.js) without stepping on it.
4
Create an agent when a user signs up or activates AI features
Hook into your existing post-sign-in flow. For Clerk, that is a webhook or a server action. For Auth.js, the signIn event. For better-auth, the onSignIn hook.
wherever you create user-scoped resources
import { getKavach } from '@/lib/kavach';export async function createDefaultAgent(userId: string) { const kavach = await getKavach(); const agent = await kavach.agent.create({ ownerId: userId, // stable ID from your auth provider name: 'default', type: 'autonomous', permissions: [ { resource: 'app:read:*', actions: ['read'] }, ], }); // Persist agent.token somewhere the user can access, encrypted at rest. // It is returned once and cannot be recovered. return { agentId: agent.id, token: agent.token };}
The token is shown once. Store it in your secrets store or hand it directly to the agent process. If you lose it, rotate with kavach.agent.rotate(agentId) to issue a new one.
5
Authorize in your handlers
Anywhere your agent code runs, check authorization before the call.
No by default. Kavach runs its own migrations on first boot. Set skipMigrations: true in createKavach if you want to run them yourself via kavach-cli migrate.
Can I share the session cookie with my existing auth?
Not directly. Kavach issues its own cookie for sessions created via its plugins. If you never use Kavach’s human-auth plugins (because you have Clerk / Auth.js / better-auth), you never see that cookie and there is nothing to share.
What if my user IDs change shape later?
Kavach stores ownerId as a string and never interprets it. Migrating from numeric IDs to UUIDs later means updating kavach_agents.owner_id in a single SQL update.
Does Kavach emit events I can subscribe to?
Yes, via event streaming and webhooks. Wire them to your analytics or to Stripe / PostHog / Slack.