Core library for building and serving backend workflows in WeWeb applications. This package provides the foundation for creating configurable, secure API endpoints with flexible request handling and integration with external services.
- API route handling and serving with Hono
- Dynamic workflow configuration and execution
- Security configuration with public/private access rules
- Advanced input validation and mapping
- Integration with external services via pluggable integrations
- Error handling and response formatting
- CORS support
- SSE streaming support
- Formula evaluation system
# npm
npm install @weweb/backend-core
# pnpm
pnpm add @weweb/backend-core
# yarn
yarn add @weweb/backend-core
import { serve } from '@weweb/backend-core';
// Define your backend configuration
const config = {
workflows: [
{
id: 'hello-workflow',
name: 'Hello API',
path: '/hello',
methods: ['GET'],
security: {
accessRule: 'public',
},
firstAction: 'hello_action',
actions: {
hello_action: {
id: 'hello_action',
type: 'action',
name: 'Say Hello',
actionId: 'example.say_hello',
inputMapping: {},
next: null,
},
},
},
],
integrations: [
{
slug: 'example',
_packageVersion: '1.0.0',
methods: {
say_hello: () => {
return { message: 'Hello from WeWeb Backend!' };
},
},
},
],
production: false,
};
// Start the server
serve(config);
console.log('Server running on http://localhost:8000');
The backend configuration defines the structure for your backend server:
interface BackendConfig {
workflows: Workflow[]
integrations: Integration[]
production: boolean
rolesConfig?: RolesConfig
apiKey?: string
pathPrefix?: string
corsOptions?: CorsOptions
}
Workflows define API endpoints with their HTTP methods, security settings, parameters validation, and actions:
interface Workflow {
/** Unique identifier for this workflow */
id: string
/** Name of the workflow */
name: string
/** Metadata for the workflow including path, method and security */
metadata?: WorkflowMetadata
/** Parameters for request inputs validation */
parameters?: Parameter[]
/** ID of the first action to execute in the workflow */
firstAction: string
/** ID of the first action to execute in the error path, or null if not handled */
firstErrorAction?: string | null
/** Map of actions keyed by their ID */
actions: Record<string, WorkflowAction>
}
interface WorkflowMetadata {
/** URL path for this endpoint (e.g., "/users" or "/products/:id") */
path?: string
/** HTTP method this endpoint supports (GET, POST, etc.) */
method: HttpMethod
/** Security configuration for this endpoint */
security?: SecurityConfig
}
interface Parameter {
/** Type of the parameter */
type: 'string' | 'number' | 'boolean' | 'object' | 'array'
/** Name of the parameter */
name: string
/** Whether this parameter is required */
required?: boolean
}
interface SecurityConfig {
/** Whether the endpoint is public or private */
accessRule: 'public' | 'private'
/** List of roles that have access when accessRule is "private" */
accessRoles?: string[]
/** How to combine multiple roles: "OR" (any role grants access) or "AND" (all roles required) */
accessRolesCondition?: 'OR' | 'AND'
}
Integrations allow external services to be accessed through defined methods:
interface Integration {
slug: string
_packageVersion: string
methods: {
[slug: string]: (...args: any[]) => MaybePromise<any>
}
}
Define parameters for request validation:
const workflow = {
// ...
parameters: [
{
type: 'string',
name: 'name',
required: true
},
{
type: 'string',
name: 'email',
required: true
}
],
// ...
};
Configure endpoints with public or private access rules:
const workflow = {
// ...
metadata: {
security: {
accessRule: 'private',
accessRoles: ['admin', 'editor'],
accessRolesCondition: 'OR', // User needs to be either admin OR editor
}
}
// ...
};
Chain multiple actions in a workflow and pass results between them:
const workflow = {
// ...
firstAction: 'get_data',
actions: {
get_data: {
id: 'get_data',
type: 'action',
name: 'Get Data',
actionId: 'example.getData',
inputMapping: {
id: '$query.id'
},
next: 'process_data',
},
process_data: {
id: 'process_data',
type: 'action',
name: 'Process Data',
actionId: 'example.processData',
inputMapping: {
data: '$results.get_data'
},
next: null,
},
},
// ...
};
Stream data to clients using Server-Sent Events by returning an AsyncIterator from your workflow:
// Example of a workflow action that returns an AsyncIterator
const streamingAction = {
id: 'stream-data',
type: 'custom-js',
name: 'Stream Large Dataset',
inputs: {},
code: `
// Define an async generator function
async function* generateData() {
for (let i = 0; i < 100; i++) {
// Simulate processing time
await new Promise(resolve => setTimeout(resolve, 100));
yield { index: i, value: Math.random() * 100 };
}
}
// Return the async iterator directly
return generateData();
`,
next: null,
};
Configure Cross-Origin Resource Sharing (CORS) options to control which domains can access your API:
const config = {
// ...other config properties
corsOptions: {
// Allow requests only from specific origins
origin: ['https://app.example.com', 'https://admin.example.com'],
// Specify allowed HTTP methods
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
// Allow specific headers
allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],
// Enable credentials (cookies, auth headers)
credentials: true,
// Cache preflight requests for 1 hour (in seconds)
maxAge: 3600,
// Expose these headers to the browser
exposeHeaders: ['Content-Length', 'X-Request-Id'],
}
};
If corsOptions
is not provided, a default permissive configuration is used:
-
origin: '*'
(allows requests from any domain) - Standard HTTP methods
- Common headers like 'Content-Type' and 'Authorization'
Use formulas to dynamically compute values from request data and previous action results:
const workflow = {
// ...
actions: {
some_action: {
// ...
inputMapping: {
computed: {
__wwtype: 'f',
code: 'context.http.query.id + context.http.body.data.value'
},
advancedComputed: {
__wwtype: 'js',
code: `
const id = parseInt(context.http.query.id);
const value = context.http.body.data.value;
return id + value;
`
}
}
}
}
};
# Run all tests
pnpm test
# Run tests with coverage
pnpm test --coverage
# Format code
pnpm format
# Run linter
pnpm lint
# Check types
pnpm typecheck
# Combined code quality check
pnpm lint && pnpm typecheck
- @weweb/backend-openai - OpenAI integration
- @weweb/backend-resend - Resend integration for email
- @weweb/backend-twilio - Twilio integration for SMS
- @weweb/backend-slack - Slack integration
- @weweb/backend-stripe - Stripe integration for payments
- @weweb/backend-pdfmonkey - PDFMonkey integration for PDF generation
MIT