Adapter API

Database and framework adapter API reference.

Database Adapters

Database adapters provide session persistence and user management. Currently, the SDK includes a Prisma adapter with full CRUD support for sessions, users, and accounts.

prismaAdapter

Prisma database adapter for session persistence

prismaAdapter(client: PrismaClient): Adapter

Parameters

clientPrismaClientrequired

Initialized Prisma client instance

Returns

Adapter

Example

import { PrismaClient } from '@prisma/client';
import { prismaAdapter } from '@warpy-auth-sdk/core';

const prisma = new PrismaClient();
const adapter = prismaAdapter(prisma);

// Use in auth config
const config = {
  secret: process.env.AUTH_SECRET!,
  provider: google({ /* ... */ }),
  adapter, // Session persistence
};

Adapter Interface

Custom adapters can be implemented by satisfying the Adapter interface:

interface Adapter {
  // Session methods
  createSession(session: Omit<Session, "sessionToken">): Promise<Session>;
  getSession(sessionToken: string): Promise<Session | null>;
  updateSession(sessionToken: string, session: Partial<Session>): Promise<Session | null>;
  deleteSession(sessionToken: string): Promise<void>;

  // User methods
  createUser(user: Omit<User, "id">): Promise<User>;
  getUser(id: string): Promise<User | null>;
  getUserByEmail(email: string): Promise<User | null>;
  updateUser(id: string, user: Partial<User>): Promise<User | null>;

  // Account methods (OAuth provider accounts)
  createAccount(account: Omit<Account, "id">): Promise<Account>;
  getAccount(provider: string, providerAccountId: string): Promise<Account | null>;
  deleteAccount(provider: string, providerAccountId: string): Promise<void>;
}

interface Session {
  sessionToken: string;
  userId: string;
  expires: Date;
}

interface User {
  id: string;
  email: string;
  name?: string;
  picture?: string;
}

interface Account {
  id: string;
  userId: string;
  provider: string; // e.g., "google", "facebook"
  providerAccountId: string;
  accessToken?: string;
  refreshToken?: string;
  expiresAt?: Date;
}

Prisma Schema

The Prisma adapter requires the following schema models:

model Session {
  sessionToken String   @id
  userId       String
  expires      DateTime
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  picture   String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Account {
  id                String    @id @default(cuid())
  userId            String
  provider          String
  providerAccountId String
  accessToken       String?   @db.Text
  refreshToken      String?   @db.Text
  expiresAt         DateTime?
  createdAt         DateTime  @default(now())
  updatedAt         DateTime  @updatedAt

  @@unique([provider, providerAccountId])
}

Framework Adapters

Framework adapters provide HTTP route handlers and middleware for popular Node.js frameworks. All adapters support PKCE OAuth, MCP integration, CAPTCHA, and protected routes.

Express Adapter

registerAuthRoutes

Register authentication routes in Express app

registerAuthRoutes(app: Express, config: AuthConfig, options?: ExpressAuthOptions): { requireAuth: Middleware }

Parameters

appExpressrequired

Express application instance

configAuthConfigrequired

Authentication configuration

optionsExpressAuthOptions

Adapter configuration options

Returns

{ requireAuth: Middleware }

Example

import express from 'express';
import { registerAuthRoutes } from '@warpy-auth-sdk/core/adapters/express';
import { google } from '@warpy-auth-sdk/core';

const app = express();

const { requireAuth } = registerAuthRoutes(app, {
  secret: process.env.AUTH_SECRET!,
  provider: google({
    clientId: process.env.GOOGLE_CLIENT_ID!,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    redirectUri: 'http://localhost:3000/auth/callback/google',
  }),
}, {
  basePath: '/auth',
  successRedirect: '/dashboard',
  errorRedirect: '/login',
  mcp: {
    enabled: true,
    path: '/api/mcp',
  },
});

// Protected route
app.get('/api/protected', requireAuth, (req, res) => {
  res.json({ user: req.session.user });
});

Fastify Adapter

registerAuthPlugin

Register authentication plugin in Fastify app

registerAuthPlugin(instance: FastifyInstance, config: AuthConfig, options?: FastifyAuthOptions): { requireAuth: Hook }

Parameters

instanceFastifyInstancerequired

Fastify instance

configAuthConfigrequired

Authentication configuration

optionsFastifyAuthOptions

Adapter configuration options

Returns

{ requireAuth: Hook }

Example

import Fastify from 'fastify';
import { registerAuthPlugin } from '@warpy-auth-sdk/core/adapters/fastify';
import { google } from '@warpy-auth-sdk/core';

const fastify = Fastify();

const { requireAuth } = registerAuthPlugin(fastify, {
  secret: process.env.AUTH_SECRET!,
  provider: google({
    clientId: process.env.GOOGLE_CLIENT_ID!,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    redirectUri: 'http://localhost:3000/auth/callback/google',
  }),
}, {
  basePath: '/auth',
  successRedirect: '/dashboard',
  errorRedirect: '/login',
});

// Protected route
fastify.get('/api/protected', { preHandler: requireAuth }, async (request, reply) => {
  return { user: request.session.user };
});

Hono Adapter

registerAuthRoutes

Register authentication routes in Hono app (multi-runtime support)

registerAuthRoutes(app: Hono, config: AuthConfig, options?: HonoAuthOptions): { requireAuth: Middleware }

Parameters

appHonorequired

Hono application instance

configAuthConfigrequired

Authentication configuration

optionsHonoAuthOptions

Adapter configuration options

Returns

{ requireAuth: Middleware }

Example

import { Hono } from 'hono';
import { registerAuthRoutes } from '@warpy-auth-sdk/core/adapters/hono';
import { google } from '@warpy-auth-sdk/core';

const app = new Hono();

const { requireAuth } = registerAuthRoutes(app, {
  secret: process.env.AUTH_SECRET!,
  provider: google({
    clientId: process.env.GOOGLE_CLIENT_ID!,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    redirectUri: 'http://localhost:3000/auth/callback/google',
  }),
}, {
  basePath: '/auth',
  successRedirect: '/dashboard',
  errorRedirect: '/login',
});

// Protected route
app.get('/api/protected', requireAuth, (c) => {
  const session = c.get('session');
  return c.json({ user: session.user });
});

Node.js HTTP Adapter

createAuthHandler

Create HTTP handler for pure Node.js (zero dependencies)

createAuthHandler(config: AuthConfig, options?: NodeAuthOptions): (req: IncomingMessage, res: ServerResponse) => Promise<boolean>

Parameters

configAuthConfigrequired

Authentication configuration

optionsNodeAuthOptions

Adapter configuration options

Returns

(req: IncomingMessage, res: ServerResponse) => Promise<boolean>

Example

import { createServer } from 'http';
import { createAuthHandler } from '@warpy-auth-sdk/core/adapters/node';
import { google } from '@warpy-auth-sdk/core';

const authHandler = createAuthHandler({
  secret: process.env.AUTH_SECRET!,
  provider: google({
    clientId: process.env.GOOGLE_CLIENT_ID!,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    redirectUri: 'http://localhost:3000/auth/callback/google',
  }),
}, {
  basePath: '/auth',
  successRedirect: '/dashboard',
  errorRedirect: '/login',
});

const server = createServer(async (req, res) => {
  const handled = await authHandler(req, res);
  if (handled) return;

  // Handle other routes
  res.writeHead(404);
  res.end('Not Found');
});

server.listen(3000);

Adapter Options

All framework adapters support the following options:

interface FrameworkAuthOptions {
  // Base path for auth routes (default: "/auth")
  basePath?: string;

  // Redirect URL after successful authentication (default: "/")
  successRedirect?: string;

  // Redirect URL after authentication error (default: "/login")
  errorRedirect?: string;

  // MCP tools configuration (optional)
  mcp?: {
    enabled?: boolean;        // Enable MCP endpoint (default: false)
    path?: string;            // MCP endpoint path (default: "/api/mcp")
    shield?: MCPShieldConfig; // Warpy Cloud Shield config (optional)
  };
}

Registered Routes

All framework adapters automatically register the following routes:

// Session management
GET  {basePath}/session           // Get current session
POST {basePath}/signout           // Sign out user

// OAuth flows
GET  {basePath}/signin            // Start OAuth (auto-detect provider)
GET  {basePath}/signin/:provider  // Start OAuth for specific provider
GET  {basePath}/callback          // OAuth callback (auto-detect provider)
GET  {basePath}/callback/:provider // OAuth callback for specific provider

// Email magic links (POST)
POST {basePath}/signin/email      // Send magic link

// Two-factor authentication (POST)
POST {basePath}/signin/twofa      // Send 2FA code
POST {basePath}/verify/twofa      // Verify 2FA code

// MCP tools (if enabled)
POST {mcpPath}                    // Execute MCP tool

Complete Express Setup

import express from 'express'; import { PrismaClient } from '@prisma/client'; import { registerAuthRoutes, prismaAdapter } from '@warpy-auth-sdk/core'; import { google } from '@warpy-auth-sdk/core'; const app = express(); const prisma = new PrismaClient(); app.use(express.json()); const { requireAuth } = registerAuthRoutes(app, { secret: process.env.AUTH_SECRET!, provider: google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, redirectUri: 'http://localhost:3000/auth/callback/google', }), adapter: prismaAdapter(prisma), callbacks: { async user(profile) { // Upsert user in database let user = await prisma.user.findUnique({ where: { email: profile.email }, }); if (!user) { user = await prisma.user.create({ data: { email: profile.email, name: profile.name, picture: profile.picture, }, }); } return user; }, }, }, { basePath: '/auth', successRedirect: '/dashboard', errorRedirect: '/login', mcp: { enabled: true, path: '/api/mcp', }, }); // Protected routes app.get('/api/user', requireAuth, (req, res) => { res.json({ user: req.session.user }); }); app.get('/api/posts', requireAuth, async (req, res) => { const posts = await prisma.post.findMany({ where: { userId: req.session.user.id }, }); res.json({ posts }); }); app.listen(3000);

Multi-Runtime Support

The Hono adapter supports multiple JavaScript runtimes:

  • Node.js: Full compatibility with Node.js HTTP server
  • Deno: Works with Deno.serve and Deno Deploy
  • Bun: Compatible with Bun.serve
  • Cloudflare Workers: Runs on Cloudflare's edge runtime

Important Notes

  • All adapters require the secret in AuthConfig for JWT signing
  • Database adapters are optional; sessions can be JWT-only (stateless)
  • Framework adapters handle PKCE cookie management automatically
  • MCP endpoints should be secured in production environments
  • Custom adapters must implement all methods in the Adapter interface
Adapter API | @warpy-auth-sdk/core