codehooks-js
v1.4.3
Published
Codehooks.io official library - provides express.JS like syntax
Maintainers
Readme
codehooks-js
The official JavaScript/TypeScript library for Codehooks.io — the agent-native backend platform. A complete backend — API routes, NoSQL database, key-value store, worker queues, cron jobs, and static asset hosting — in a single import.
Why Codehooks?
Single Cohesive Library – REST routes, NoSQL database, key-value store, queues, scheduled jobs, file storage, and real-time APIs. One library, one pattern, everything works together.
Zero Infrastructure Assembly – No AWS/GCP service configuration. No API Gateway + Lambda + DynamoDB + SQS wiring. Write code and deploy — the platform handles everything else.
AI Agent Native – The entire lifecycle is CLI-native. Any tool that can run shell commands — Claude Code, Cursor, Codex, Cline — can autonomously create, deploy, verify, and iterate on a production backend.
Sub-5-Second Deploys – Your agent can iterate 50 times in the time it takes other platforms to deploy once.
Flat-Rate Pricing – Unlimited compute included. No per-request fees, no surprise bills.
Quick Start
Install the Codehooks CLI:
npm install -g codehooksCreate a new project and install the library:
codehooks create myproject
cd myproject
npm install codehooks-jsAI Agent Setup
Claude Code Plugin (Recommended)
/plugin marketplace add RestDB/codehooks-claude-plugin
/plugin install codehooks@codehooksThen use /codehooks:backend to start building.
Built-in AI Prompt
coho prompt # Display the Codehooks development prompt
coho prompt | pbcopy # Copy to clipboard (macOS)MCP Server
For tools without terminal access (Claude Desktop, Cline, Zed): codehooks-mcp-server. Always prefer the CLI when available.
REST API Example
import { app, Datastore } from 'codehooks-js';
// REST API routes
app.get('/hello', (req, res) => {
res.json({ message: 'Hello World!' });
});
// Store and query data
app.post('/items', async (req, res) => {
const conn = await Datastore.open();
const result = await conn.insertOne('items', req.body);
res.json(result);
});
// Auto-generate CRUD REST API for any collection
app.crudlify();
export default app.init();Webhook Handler Example
Handle incoming webhooks with signature verification and reliable background processing:
import { app, datastore } from 'codehooks-js';
import crypto from 'crypto';
// Webhook endpoint with HMAC signature verification
app.post('/webhooks/incoming', async (req, res) => {
const signature = req.headers['x-webhook-signature'];
const secret = process.env.WEBHOOK_SECRET;
// Use rawBody for signature verification (preserves exact bytes)
const expectedSig = crypto
.createHmac('sha256', secret)
.update(req.rawBody)
.digest('hex');
if (signature !== expectedSig) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Store the webhook event
const conn = await datastore.open();
const event = await conn.insertOne('webhook_events', {
payload: req.body,
received: new Date()
});
// Queue for reliable background processing
await conn.enqueue('processWebhook', { eventId: event._id });
res.json({ received: true });
});
// Background worker with automatic retries
app.worker('processWebhook', async (req, res) => {
const { eventId } = req.body.payload;
const conn = await datastore.open();
const event = await conn.getOne('webhook_events', eventId);
console.log('Processing webhook:', event.payload);
// Your processing logic here
res.end();
});
export default app.init();TypeScript Support
Full TypeScript support with strong types:
import { app, datastore, httpRequest, httpResponse } from 'codehooks-js';
app.post('/webhooks/github', async (req: httpRequest, res: httpResponse) => {
const event = req.headers['x-github-event'];
const payload = req.body;
const conn = await datastore.open();
await conn.insertOne('github_events', {
event,
payload,
timestamp: new Date()
});
res.json({ status: 'ok' });
});
export default app.init();OpenAPI Documentation
Automatically generate interactive API documentation with Swagger UI:
import { app } from 'codehooks-js';
import { z } from 'zod';
const userSchema = z.object({
name: z.string().min(1).describe('User name'),
email: z.string().email().describe('Email address'),
role: z.enum(['admin', 'user']).default('user')
});
app.openapi({
info: { title: 'My API', version: '1.0.0' }
});
app.crudlify({ users: userSchema });
export default app.init();After deploying, visit /docs for Swagger UI or /openapi.json for the spec.
Supports Zod, Yup, and JSON Schema for validation and documentation. See OpenAPI Documentation for details.
Compile
When running the coho compile command, it will automatically create a tsconfig.json file in the project directory. The tsconfig file can be further adapted to your needs, the initial configuration is shown in the example below:
{
"files": ["./index.ts"],
"compilerOptions": {
"allowJs": true,
"lib": ["ES6", "dom"]
}
}Any syntax or type error will be displayed accordingly from the compile command, for example:
$ coho compile
🤔 [tsl] ERROR in /Users/jane/projects/tsdemo/index.ts(9,9)
TS2345: Argument of type '(req: httpRequest, res: httpResponse) => void' is not assignable to parameter of type 'string'.Correcting the errors should ultimately show a successfull compile output, ready for deployment of your backend app.
$ coho compile
OK 🙌Your backend application is now available at your project's endpoint URL. For example:
https://myproject-ff00.codehooks.io/dev/*
Deploy
From the project directory run:
$ codehooks deployWhat You Can Build
- Webhook Handlers – Receive and process webhooks from Stripe, Shopify, GitHub, Slack, Discord, Twilio, and any service. Built-in
request.rawBodyfor signature verification. - REST APIs – Express.js-like routing with
app.get(),app.post(), etc. Full CRUD withapp.crudlify(). - AI Agent Tool Backends – Give your agents APIs they can call — store data, trigger workflows, query results.
- Scheduled Automations – Cron jobs that sync data, send digests, clean up records, or poll external APIs.
- Multi-Step Workflows – Chain API calls, queue tasks, and orchestrate services with the Workflow API. Automatic retries, state persistence, and error recovery.
- SaaS Integrations – Connect any service that sends webhooks. Process, transform, and route to where it matters.
- Full-Stack Apps – Deploy frontend and backend together in one package. React, static sites, or SPAs served alongside your API with zero extra config.
Documentation
For complete documentation, visit https://codehooks.io/docs.
For AI-optimized documentation, see https://codehooks.io/llms.txt.
API
Codehooks Class API Reference
The Codehooks class provides a comprehensive backend application framework with the following APIs:
HTTP Routing APIs
post(path, ...hook)- Register POST route handlersget(path, ...hook)- Register GET route handlersput(path, ...hook)- Register PUT route handlerspatch(path, ...hook)- Register PATCH route handlersdelete(path, ...hook)- Register DELETE route handlersall(path, ...hook)- Register handlers for all HTTP methods
Middleware & Authentication APIs
use(...hook)- Register global middleware (supports string paths, RegExp, or function)useRoute(route, ...hook)- Register route-specific middlewareauth(path, ...hook)- Register authentication middleware for specific paths
Background Processing APIs
queue(topic, ...hook)- Register queue handlers for background processingworker(name, ...hook)- Register worker functions (also adds to queues for legacy support)job(cronExpression, ...hook)- Register scheduled cron jobs
Static File Serving APIs
static(options, hook)- Serve static files from source code directorystorage(options, hook)- Serve files from blob storage directory
Template & Configuration APIs
set(key, val)- Set application configuration settingsrender(view, data, cb)- Render templates with datacrudlify(schema, options)- Auto-generate CRUD REST API endpointsopenapi(config, uiPath)- Enable OpenAPI/Swagger documentation at/docsand/openapi.json
Real-time Communication APIs
realtime(path, ...hook)- Set up server-sent events (SSE) channels for real-time communication
Workflow Management APIs
createWorkflow(name, description, steps, options)- Create and register a new workflow instance
Application Lifecycle APIs
init(hook)- Initialize the application and return manifeststart(hook)- Alias forinit()method
The Codehooks class serves as a comprehensive backend application framework that combines HTTP routing, background processing, real-time communication, and workflow management capabilities in a single, cohesive API.
Datastore API Reference
The Datastore provides a unified interface for both NoSQL document storage and Key-Value operations. It supports MongoDB-like query syntax and provides streaming capabilities for large datasets.
Connection & Collection Management
open()- Connect to the Datastore and return the API interfacecollection(name)- Get a NoSQL collection by name for document operations
NoSQL Document Operations
Read Operations
getOne(collection, query)- Get a single document by ID or queryfindOne(collection, query)- Alias for getOnegetMany(collection, query?, options?)- Get a stream of documents matching queryfind(collection, query?, options?)- Alias for getMany
Write Operations
insertOne(collection, document)- Insert a new document into a collectionupdateOne(collection, query, document, updateOperators?, options?)- Update one document (patches existing data)updateMany(collection, query, document, updateOperators?)- Update multiple documentsreplaceOne(collection, query, document, options?)- Replace one document completelyreplaceMany(collection, query, document, options?)- Replace multiple documents
Delete Operations
removeOne(collection, query)- Remove one document by ID or queryremoveMany(collection, query)- Remove multiple documents matching query
Schema Management
createSchema(collection, schema)- Validate collection data against JSON-SchemasetSchema(collection, schema)- Alias for createSchemaremoveSchema(collection)- Remove JSON-schema validation for collectiongetSchema(collection)- Get JSON-schema for collection
Utility Operations
count(collection)- Count documents in a collection
Key-Value Operations
Basic Key-Value Operations
set(key, value, options?)- Set a key-value pairget(key, options?)- Get a value by keygetAll(keyPattern, options?)- Get all key-value pairs matching patterndel(key, options?)- Delete a key-value pairdelAll(keyPattern, options?)- Delete all key-value pairs matching pattern
Numeric Operations
incr(key, value, options?)- Increment a numeric valuedecr(key, value, options?)- Decrement a numeric value
Queue Operations
enqueue(topic, document, options?)- Add a job to a queue for background processingenqueueFromQuery(collection, query, topic, options?)- Queue each item from a database query
DataStream Interface
When using getMany() or find(), you get a DataStream object with these methods:
on(event, callback)- Listen for data events (e.g.,'data','end')json(response)- Pipe data directly to HTTP response as JSONtoArray()- Convert stream to array of objectsforEach(callback)- Iterate over each object in the stream
Usage Examples
import { datastore } from 'codehooks-js';
// Connect to datastore
const conn = await datastore.open();
// NoSQL operations
const doc = await conn.insertOne('users', {
name: 'John',
email: '[email protected]',
});
const user = await conn.getOne('users', { _id: doc._id });
const users = await conn.getMany('users', { active: true }).toArray();
await conn.updateOne('users', { _id: doc._id }, { lastLogin: new Date() });
// Key-Value operations
await conn.set('user:123:session', { token: 'abc123', expires: new Date() });
const session = await conn.get('user:123:session');
await conn.incr('visits', 1);
// Queue operations
await conn.enqueue('emailWorker', {
to: '[email protected]',
template: 'welcome',
});Query Syntax
The Datastore supports MongoDB-like query syntax:
// Simple equality
{
status: 'active';
}
// Comparison operators
{
age: {
$gt: 18;
}
}
{
price: {
$lte: 100;
}
}
// Logical operators
{
$and: [{ status: 'active' }, { age: { $gte: 18 } }];
}
{
$or: [{ category: 'A' }, { category: 'B' }];
}
// Array operations
{
tags: {
$in: ['javascript', 'nodejs'];
}
}
{
tags: {
$all: ['javascript', 'nodejs'];
}
}
// Regular expressions
{
name: {
$regex: /john/i;
}
}Options
Many operations accept an options object for additional configuration:
// Upsert option for updates
await conn.updateOne(
'users',
{ email: '[email protected]' },
{ lastLogin: new Date() },
{},
{ upsert: true }
);
// Key-Value options
await conn.set('key', 'value', { ttl: 3600000 }); // 1 hour TTLKey Features:
- Express-style routing with support for all HTTP methods
- Middleware system with global and route-specific middleware
- Background processing with queues, workers, and scheduled jobs
- Static file serving from both source and blob storage
- Real-time communication via Server-Sent Events
- Workflow engine for complex step-based applications
- Auto-generated CRUD APIs with schema validation
- Datastore with MongoDB-like query syntax, key-value operations, and queue management
- Security & Authentication with JWKS support and custom auth middleware for secure API endpoints
