This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This repository contains example applications demonstrating various capabilities of the Codehooks.io serverless backend platform. Each subdirectory is a standalone example showcasing different features like CRUD APIs, real-time communication, file handling, authentication, and integrations with external services.
Every Codehooks.io backend follows this essential structure:
import { app } from 'codehooks-js'
// Define routes
app.get('/path', async (req, res) => { /* ... */ })
app.post('/path', async (req, res) => { /* ... */ })
// MANDATORY: bind to serverless runtime
export default app.init()Critical: All backend files MUST end with export default app.init() to bind to the serverless runtime.
app- HTTP server instance (Express-like API)Datastore- NoSQL database for persistent storagerealtime- Server-Sent Events (SSE) for real-time client communicationcrudlify- Auto-generates REST CRUD endpoints from schemas
Example with all features:
import { app, Datastore, realtime } from 'codehooks-js'
import crudlify from 'codehooks-crudlify'const conn = await Datastore.open()
// Insert
const result = await conn.insertOne('collection', { field: 'value' })
// Query
const doc = await conn.getOne('collection', documentId)
const docs = await conn.getMany('collection', { query }, { sort, limit }).toArray()
// Update
await conn.updateOne('collection', documentId, {
'$set': { field: 'newValue' },
'$push': { arrayField: item }
})// Server: Create channel and listener
realtime.createChannel('/channelName')
app.post('/connect', async (req, res) => {
const listenerData = await realtime.createListener('/channelName', interests)
res.json({ listenerID: listenerData._id })
})
// Server: Publish events to all listeners
await realtime.publishEvent('/channelName', { type: 'event', data: {...} })
// Client connects to: GET /channelName/:listenerID
// Receives events via EventSourceimport crudlify from 'codehooks-crudlify'
// Creates full REST API (GET, POST, PUT, DELETE) for each collection
crudlify(app, { customers, products })
// Optionally with Yup schema validation (see crud/schema.js)// Serve static files from /public directory
app.static({
route: '/public',
directory: '/public'
})
// Serve SPA with client-side routing
app.static({
route: '/app',
directory: '/dist',
default: 'index.html',
notFound: '/index.html' // Essential for React Router, etc.
})// Apply to all routes
app.auth('/*', (req, res, next) => {
// Validation logic
next() // or res.status(403).end()
})
// Apply to specific routes
app.auth('/admin/*', (req, res, next) => { /* ... */ })// Run scheduled tasks (cron format: minute hour day month weekday)
app.job('0 2 * * *', async (req, res) => {
// Runs daily at 2:00 AM
console.log('Running scheduled task')
res.end() // Signal completion
})crud/- Auto-CRUD with Yup schema validationrealtime-chat/- SSE-based chataws-s3/- Binary file streaming to/from S3binary-streams/- Direct binary stream handlingmailgun/,mailgunexample/- Email integrationmongodb-external/- External MongoDB connectionchatgpt-rest-api/- OpenAI API integration
react-workflow-client/- React frontend + Codehooks backend with Workflow API and SSEnextjs-todo/- Next.js app consuming Codehooks CRUD APIreact-backend-example/- React with custom backendsvelte-todo/- Svelte consuming backend APIalpinejs-dataadmin/- Alpine.js admin interfacealpinejs-players/- Alpine.js with backend
dynamicweb/- Server-side template renderingbsgenerator/- Static site deploymentstatic/- Pure static file serving
# Initialize new Codehooks project (one-time)
coho init
# Deploy code
coho deploy
# Deploy with file upload
coho deploy --upload
# Get project info (URL, token)
coho info# Upload directory to backend
coho upload --src './public' --target '/public'
coho file-upload --src './app' --target '/app'# React/Next.js/Svelte projects
npm install
npm run dev # Development server
npm run build # Production build
npm run preview # Preview production build# 1. Build frontend
npm run build
# 2. Deploy backend with built assets
cd codehooks-server # or backend directory
coho deploy --upload- Navigate to example directory
- Check for
package.jsondependencies - Install:
npm install - Initialize:
coho init(if needed) - Deploy:
coho deploy - Get URL:
coho info
- Review README.md for specific setup
- Check for
.env.exampleor environment variables needed - Build frontend:
npm run build - Deploy backend (see example's package.json scripts)
- For local development:
- Frontend:
npm run dev(usually port 3000) - Backend: deploy to Codehooks.io or use mock service
- Frontend:
Full-stack examples typically need:
# .env or .env.local
VITE_API_URL=https://your-project.codehooks.io
VITE_API_TOKEN=your-api-token
# or for Next.js:
SERVER_URL=https://your-project.codehooks.io
API_TOKEN=your-api-tokenGet these values from: coho info
example-project/
├── index.js # Backend entry point
├── package.json # Dependencies
├── schema.js # Data schemas (if using crudlify)
├── middleware.js # Custom middleware (if needed)
├── public/ or dist/ # Static files (if full-stack)
└── README.md
app.get('/endpoint', async (req, res) => {
try {
// Logic
res.json({ success: true, data })
} catch (error) {
console.error('Error:', error)
res.status(500).json({
error: 'Description',
message: error.message
})
}
})When working with files (see aws-s3/ or binary-streams/):
import { PassThrough } from 'stream'
// Receiving upload
req.pipe(destinationStream)
// Sending download
res.set('content-type', contentType)
sourceStream.pipe(res.writable)The react-workflow-client/ example demonstrates the Workflow API for stateful, step-based processes:
import { workflow } from 'codehooks-js'
const myWorkflow = workflow.create('workflowName')
.step('stepName', async (state) => {
// Step logic
return { ...state, updatedField: value }
})
.waitFor('userInput') // Pause for external event
.step('nextStep', async (state) => { /* ... */ })
// Start workflow
const instance = await myWorkflow.start(initialState)
// Continue after wait
await myWorkflow.updateState(instanceId, newData, { continue: true })- No server.listen() - Use
app.init()instead - Stateless - Each request is independent; use Datastore for persistence
- Environment variables - Set via Codehooks dashboard or CLI
- File system - Limited; use Datastore, external storage (S3), or static uploads
- CORS - Built-in by default, no additional middleware needed
- Main documentation: https://codehooks.io/docs
- CRUD library: https://www.npmjs.com/package/codehooks-crudlify
- Real-time API: https://codehooks.io/docs/realtimeapi
- Workflow API: https://codehooks.io/docs/workflow-api
- CLI reference: https://codehooks.io/docs/cli