@clad-ai/node
v0.1.1
Published
Node.js/TypeScript SDK for seamless integration of dynamic monetization into LLM-driven server workflows.
Maintainers
Readme
@clad-ai/node
Table of Contents
- Overview
- Installation
- Node.js Version Support
- Instantiating CladClient
- Core Concepts
- Methods
- Framework Integration Examples
- TypeScript Support
- JavaScript Usage
- Error Handling
- Support
Overview
Clad provides a lightweight Node.js/TypeScript SDK for secure, low-latency native ad injection in LLM workflows on server-side applications. Built specifically for server environments, this SDK offers flexible processing modes to match your infrastructure needs.
Key Features:
- 🚀 Three processing modes for different performance and infrastructure needs
- 📦 Dual package support - Works with both TypeScript and JavaScript
- 🔄 Multiple Node.js versions - Compatible with Node.js 16+
- 🏗️ Framework agnostic - Works with Express, Fastify, Next.js, and more
- 🔧 Production ready - Built-in Redis support, error handling, and fallbacks
⚠️ This SDK is proprietary and intended for authorized Clad Labs clients only. Use or redistribution without permission is strictly prohibited.
Installation
npm install @clad-ai/nodeFor Redis support (optional):
npm install redisNode.js Version Support
- Node.js 14+: Full compatibility with node-fetch v2
- Node.js 16+: Recommended for optimal performance
- Node.js 18+: Native fetch available but uses node-fetch for consistency
- TypeScript: Full type definitions included
- JavaScript: Dual package support (CommonJS and ESM)
- Module Systems: Works with both
require()andimportstatements
Instantiating CladClient
Before calling any method, create an instance of CladClient with your API key:
TypeScript
import { CladClient } from '@clad-ai/node';
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY!,
threshold: 3, // Optional: messages before triggering API (default: 3)
filteredKeywords: ['gambling', 'crypto', 'adult'] // Optional: filter keywords
});JavaScript (CommonJS)
const { CladClient } = require('@clad-ai/node');
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY,
threshold: 5
});JavaScript (ESM)
import { CladClient } from '@clad-ai/node';
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY
});Configuration Parameters:
apiKey: string— API key provided by Clad. Contact [email protected] to get yours.threshold?: number— Optional. Number of messages before triggering an API call. Defaults to 3.filteredKeywords?: string[]— Optional. Keywords to filter out specific ads from being displayed.redisClient?: any— Optional. Redis client forgetProcessedInputWithRedismethod.
Core Concepts
✅ Three modes of operation:
Each mode offers a different balance of speed, memory footprint, and infrastructure requirements. These trade-offs let you choose the best fit for your scale, cost, and reliability needs.
getProcessedInput: Fast with local server RAM for counting and contextgetProcessedInputFullyManaged: Zero local memory, fully server-managed stategetProcessedInputWithRedis: Production-ready with Redis for scaling across servers
Methods
Important: All methods require a userId parameter. In backend environments, this user ID should be passed from your frontend application (which can use the @clad-ai/react SDK's getOrCreateUserId() function to generate and persist user IDs in localStorage). Do not generate user IDs on the backend as they will not persist across requests.
getProcessedInput
Mode 1: Local Memory (Fast & Lightweight)
Uses in-process memory for ultra-fast message counting and context tracking. Ideal for single-server deployments or when you want minimal external dependencies.
Usage:
const response = await cladClient.getProcessedInput(
"I'm looking for running shoes",
userId,
"false" // discrete mode
);
console.log(response.prompt); // Final prompt with or without adParameters:
userInput: string— User's chat inputuserId: string— Persistent user ID (typically from frontend)discrete: 'true' | 'false'— Whether to mark ad content explicitly (default: 'false')
Returns:
{
prompt: string;
promptType: 'clean' | 'injected';
link: string;
discrete: 'true' | 'false';
adType?: string;
image_url?: string;
}getProcessedInputFullyManaged
Mode 2: Zero Memory (Fully Server-Managed)
This mode uses no local memory. All counting, context, and injection logic is handled by Clad's backend. Every message is sent to the API, adding slight network latency but requiring zero local state management.
Usage:
const response = await cladClient.getProcessedInputFullyManaged(
"Looking for coffee shops nearby",
userId,
"false",
5 // Optional: override threshold for this request
);Parameters:
- Same as
getProcessedInput, plus: threshold?: number— Optional threshold override for this specific request
Returns:
Same as getProcessedInput, plus optional _error field for debugging.
getProcessedInputWithRedis
Mode 3: Production-Ready (Redis-Enhanced)
🏆 Recommended for production environments
This mode uses Redis for persistent, scalable state management. Perfect for multi-server deployments, providing fast performance with centralized state. Falls back gracefully to local cache if Redis is unavailable.
Setup:
import { createClient } from 'redis';
const redisClient = createClient({
url: 'redis://localhost:6379'
});
await redisClient.connect();
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY!,
redisClient: redisClient
});Usage:
const response = await cladClient.getProcessedInputWithRedis(
"Book a hotel in Paris",
userId,
"false"
);Parameters:
Same as getProcessedInput.
Returns:
Same as getProcessedInput, plus optional _error field for debugging.
Framework Integration Examples
Express.js
import express from 'express';
import { CladClient } from '@clad-ai/node';
const app = express();
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY!
});
app.post('/api/chat', async (req, res) => {
const { message, userId } = req.body;
try {
const result = await cladClient.getProcessedInput(message, userId);
// Send processed prompt to your LLM
const llmResponse = await yourLLM.generate(result.prompt);
res.json({
response: llmResponse,
adInfo: result.promptType === 'injected' ? {
link: result.link,
adType: result.adType
} : null
});
} catch (error) {
res.status(500).json({ error: 'Processing failed' });
}
});Fastify
import Fastify from 'fastify';
import { CladClient } from '@clad-ai/node';
const fastify = Fastify();
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY!
});
fastify.post('/api/chat', async (request, reply) => {
const { message, userId } = request.body as any;
const result = await cladClient.getProcessedInputFullyManaged(
message,
userId
);
return { processedPrompt: result.prompt };
});Next.js API Routes
// pages/api/chat.ts or app/api/chat/route.ts
import { CladClient } from '@clad-ai/node';
const cladClient = new CladClient({
apiKey: process.env.CLAD_API_KEY!
});
export async function POST(request: Request) {
const { message, userId } = await request.json();
const result = await cladClient.getProcessedInput(message, userId);
return Response.json({
prompt: result.prompt,
hasAd: result.promptType === 'injected'
});
}TypeScript Support
Full TypeScript definitions are included:
import {
CladClient,
ProcessedUserInputResponse,
CladClientConfig
} from '@clad-ai/node';
const config: CladClientConfig = {
apiKey: 'your-key',
threshold: 3
};
const client = new CladClient(config);
const response: ProcessedUserInputResponse = await client.getProcessedInput(
'Hello world',
'user-123'
);JavaScript Usage
The SDK works seamlessly with plain JavaScript:
const { CladClient } = require('@clad-ai/node');
const client = new CladClient({
apiKey: process.env.CLAD_API_KEY
});
// Async/await
const response = await client.getProcessedInput('Hello', 'user-123');
// Promises
client.getProcessedInput('Hello', 'user-123')
.then(response => console.log(response.prompt))
.catch(error => console.error(error));Error Handling
The SDK provides comprehensive error handling:
const response = await cladClient.getProcessedInputFullyManaged(
message,
userId
);
// Check for errors
if ('_error' in response && response._error) {
console.error('API Error:', response._error.status, response._error.message);
// Response still contains fallback clean prompt
}
// Redis method with try/catch
try {
const response = await cladClient.getProcessedInputWithRedis(message, userId);
} catch (error) {
if (error.message.includes('Redis client not configured')) {
// Handle Redis configuration error
}
}Error Response Format:
{
prompt: string; // Always present (fallback to original input)
promptType: 'clean'; // Always 'clean' on error
link: ''; // Empty on error
discrete: 'false'; // Default value
_error?: { // Present when error occurs
status?: number; // HTTP status code (if applicable)
message: string; // Error description
}
}Support
For help, email us at [email protected]
This software is proprietary and confidential.
Unauthorized copying, distribution, or use of this software is strictly prohibited without express written permission from Clad Labs.
© 2025 Clad Labs. All rights reserved.
