API Reference

Express.js

Complete Express server with session management:

import express from 'express';
import cors from 'cors';
import { OblienClient, OblienChat } from 'oblien';

const app = express();

app.use(cors());
app.use(express.json());

// Initialize Oblien
const client = new OblienClient({
  clientId: process.env.OBLIEN_CLIENT_ID,
  clientSecret: process.env.OBLIEN_CLIENT_SECRET
});

const chat = new OblienChat(client);

// Authenticated session
app.post('/api/session', requireAuth, async (req, res) => {
  try {
    const session = await chat.createSession({
      agentId: req.body.agentId,
      namespace: req.user.id,
      workspace: {
        app_id: req.body.workspaceId,
        user: {
          name: req.user.name,
          email: req.user.email
        }
      }
    });
    
    res.json(session);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Guest session
app.post('/api/guest-session', async (req, res) => {
  try {
    const ip = req.ip || req.headers['x-forwarded-for'];
    
    const session = await chat.createGuestSession({
      ip,
      fingerprint: req.body.fingerprint,
      agentId: req.body.agentId,
      metadata: {
        userAgent: req.headers['user-agent']
      }
    });
    
    res.json(session);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// List user sessions
app.get('/api/sessions', requireAuth, async (req, res) => {
  try {
    const sessions = await chat.listSessions({
      namespace: req.user.id
    });
    
    res.json(sessions);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Delete session
app.delete('/api/session/:id', requireAuth, async (req, res) => {
  try {
    await chat.deleteSession(req.params.id);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Next.js App Router

API Routes

// app/api/session/create/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { OblienClient, OblienChat } from 'oblien';
import { getServerSession } from 'next-auth';

const client = new OblienClient({
  clientId: process.env.OBLIEN_CLIENT_ID!,
  clientSecret: process.env.OBLIEN_CLIENT_SECRET!
});

const chat = new OblienChat(client);

export async function POST(req: NextRequest) {
  const session = await getServerSession();
  
  if (!session?.user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  
  const { agentId } = await req.json();
  
  const chatSession = await chat.createSession({
    agentId,
    namespace: session.user.id
  });
  
  return NextResponse.json(chatSession);
}
// app/api/session/guest/route.ts
export async function POST(req: NextRequest) {
  const { fingerprint, agentId } = await req.json();
  const ip = req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip');
  
  const session = await chat.createGuestSession({
    ip: ip || '0.0.0.0',
    fingerprint,
    agentId
  });
  
  return NextResponse.json(session);
}

Server Actions

// app/actions/chat.ts
'use server';

import { OblienClient, OblienChat } from 'oblien';
import { auth } from '@/lib/auth';

const client = new OblienClient({
  clientId: process.env.OBLIEN_CLIENT_ID!,
  clientSecret: process.env.OBLIEN_CLIENT_SECRET!
});

const chat = new OblienChat(client);

export async function createChatSession(agentId: string) {
  const session = await auth();
  
  if (!session?.user) {
    throw new Error('Unauthorized');
  }
  
  return await chat.createSession({
    agentId,
    namespace: session.user.id
  });
}

export async function createGuestSession(agentId: string, fingerprint: string) {
  // Get IP from headers in route handler
  return await chat.createGuestSession({
    ip: '0.0.0.0', // Set from request
    fingerprint,
    agentId
  });
}

Next.js Pages Router

// pages/api/session/create.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { OblienClient, OblienChat } from 'oblien';
import { getSession } from 'next-auth/react';

const client = new OblienClient({
  clientId: process.env.OBLIEN_CLIENT_ID!,
  clientSecret: process.env.OBLIEN_CLIENT_SECRET!
});

const chat = new OblienChat(client);

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }
  
  const session = await getSession({ req });
  
  if (!session?.user) {
    // Create guest session
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    const { fingerprint, agentId } = req.body;
    
    const guestSession = await chat.createGuestSession({
      ip: ip as string,
      fingerprint,
      agentId
    });
    
    return res.json(guestSession);
  }
  
  // Create authenticated session
  const { agentId } = req.body;
  
  const chatSession = await chat.createSession({
    agentId,
    namespace: session.user.id
  });
  
  res.json(chatSession);
}

Fastify

import Fastify from 'fastify';
import { OblienClient, OblienChat } from 'oblien';

const fastify = Fastify();

const client = new OblienClient({
  clientId: process.env.OBLIEN_CLIENT_ID!,
  clientSecret: process.env.OBLIEN_CLIENT_SECRET!
});

const chat = new OblienChat(client);

fastify.post('/api/session', async (request, reply) => {
  const { agentId, userId } = request.body;
  
  const session = await chat.createSession({
    agentId,
    namespace: userId
  });
  
  return session;
});

fastify.post('/api/guest-session', async (request, reply) => {
  const { fingerprint, agentId } = request.body;
  const ip = request.ip;
  
  const session = await chat.createGuestSession({
    ip,
    fingerprint,
    agentId
  });
  
  return session;
});

fastify.listen({ port: 3000 });

NestJS

// session.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { OblienClient, OblienChat } from 'oblien';

@Injectable()
export class SessionService {
  private client: OblienClient;
  private chat: OblienChat;
  
  constructor(private configService: ConfigService) {
    this.client = new OblienClient({
      apiKey: this.configService.get('OBLIEN_API_KEY')!,
      apiSecret: this.configService.get('OBLIEN_API_SECRET')!
    });
    
    this.chat = new OblienChat(this.client);
  }
  
  async createSession(agentId: string, userId: string) {
    return await this.chat.createSession({
      agentId,
      namespace: userId
    });
  }
  
  async createGuestSession(agentId: string, ip: string, fingerprint?: string) {
    return await this.chat.createGuestSession({
      ip,
      fingerprint,
      agentId
    });
  }
}
// session.controller.ts
import { Controller, Post, Body, Req } from '@nestjs/common';
import { SessionService } from './session.service';

@Controller('api/session')
export class SessionController {
  constructor(private sessionService: SessionService) {}
  
  @Post('create')
  async createSession(@Body() body: { agentId: string; userId: string }) {
    return await this.sessionService.createSession(
      body.agentId,
      body.userId
    );
  }
  
  @Post('guest')
  async createGuestSession(
    @Body() body: { agentId: string; fingerprint?: string },
    @Req() req: Request
  ) {
    return await this.sessionService.createGuestSession(
      body.agentId,
      req.ip,
      body.fingerprint
    );
  }
}

Environment Variables

Create .env file:

OBLIEN_API_KEY=your_api_key
OBLIEN_API_SECRET=your_api_secret

Load in your application:

// Using dotenv
import 'dotenv/config';

// Or Next.js (automatic)
// Just create .env.local file

Error Handling

try {
  const session = await chat.createSession({
    agentId: 'agent-123',
    namespace: 'user-456'
  });
} catch (error) {
  if (error.response?.status === 401) {
    console.error('Invalid API credentials');
  } else if (error.response?.status === 404) {
    console.error('Agent not found');
  } else if (error.response?.status === 429) {
    console.error('Rate limit exceeded');
  } else {
    console.error('Error creating session:', error.message);
  }
}

TypeScript Support

import type {
  OblienClient,
  OblienChat,
  SessionData,
  Guest
} from 'oblien';

const session: SessionData = await chat.createSession({
  agentId: 'agent-123',
  namespace: 'user-456'
});

Testing

import { describe, it, expect, beforeAll } from 'vitest';
import { OblienClient, OblienChat } from 'oblien';

describe('Session Management', () => {
  let chat: OblienChat;
  
  beforeAll(() => {
    const client = new OblienClient({
      apiKey: process.env.TEST_API_KEY!,
      apiSecret: process.env.TEST_API_SECRET!
    });
    chat = new OblienChat(client);
  });
  
  it('should create session', async () => {
    const session = await chat.createSession({
      agentId: 'test-agent',
      namespace: 'test-user'
    });
    
    expect(session).toHaveProperty('sessionId');
    expect(session).toHaveProperty('token');
  });
  
  it('should create guest session', async () => {
    const session = await chat.createGuestSession({
      ip: '127.0.0.1',
      fingerprint: 'test-fingerprint',
      agentId: 'test-agent'
    });
    
    expect(session).toHaveProperty('guest');
    expect(session.guest).toHaveProperty('id');
  });
});

Next Steps