Configuration Reference

Complete reference for all SonicJS configuration options including application settings, Cloudflare bindings, environment variables, and plugin configuration.


Overview

SonicJS configuration happens at multiple levels:

  1. Application Config - TypeScript configuration passed to createSonicJSApp()
  2. Environment Bindings - Cloudflare Workers bindings (D1, KV, R2)
  3. Environment Variables - Runtime configuration via wrangler.toml or secrets
  4. Plugin Config - Individual plugin settings

Application Config

The main configuration object passed when creating your SonicJS application.

SonicJSConfig Interface

interface SonicJSConfig {
  // Collections configuration
  collections?: {
    directory?: string     // Path to collection definitions
    autoSync?: boolean     // Auto-sync collections on startup
  }

  // Plugins configuration
  plugins?: {
    directory?: string     // Path to custom plugins
    autoLoad?: boolean     // Auto-load plugins from directory
    disableAll?: boolean   // Disable all plugins (including core)
  }

  // Custom routes
  routes?: Array<{
    path: string           // Route path prefix
    handler: Hono          // Hono router instance
  }>

  // Custom middleware
  middleware?: {
    beforeAuth?: Middleware[]   // Run before authentication
    afterAuth?: Middleware[]    // Run after authentication
  }

  // App metadata
  version?: string         // Application version
  name?: string            // Application name
}

Basic Usage

Basic Configuration

import { createSonicJSApp } from '@sonicjs-cms/core'

const app = createSonicJSApp({
  name: 'My CMS',
  version: '1.0.0',
  collections: {
    directory: './src/collections',
    autoSync: true
  },
  plugins: {
    directory: './src/plugins',
    autoLoad: true
  }
})

export default app

With Custom Routes

Custom Routes

import { createSonicJSApp } from '@sonicjs-cms/core'
import { Hono } from 'hono'

// Custom API routes
const customApi = new Hono()
customApi.get('/hello', (c) => c.json({ message: 'Hello!' }))
customApi.post('/webhook', async (c) => {
  const body = await c.req.json()
  // Handle webhook
  return c.json({ success: true })
})

const app = createSonicJSApp({
  routes: [
    { path: '/api/custom', handler: customApi }
  ]
})

export default app

With Custom Middleware

Custom Middleware

import { createSonicJSApp } from '@sonicjs-cms/core'

const app = createSonicJSApp({
  middleware: {
    beforeAuth: [
      // Rate limiting middleware
      async (c, next) => {
        // Check rate limits
        await next()
      },
      // Request logging
      async (c, next) => {
        console.log(`${c.req.method} ${c.req.url}`)
        await next()
      }
    ],
    afterAuth: [
      // Audit logging (after user is known)
      async (c, next) => {
        const user = c.get('user')
        console.log(`User ${user?.email} accessing ${c.req.url}`)
        await next()
      }
    ]
  }
})

export default app

Environment Bindings

Cloudflare Workers bindings required by SonicJS.

Bindings Interface

interface Bindings {
  // Required bindings
  DB: D1Database              // Cloudflare D1 database
  CACHE_KV: KVNamespace       // Cloudflare KV for caching
  MEDIA_BUCKET: R2Bucket      // Cloudflare R2 for media storage
  ASSETS: Fetcher             // Static assets fetcher

  // Optional bindings
  EMAIL_QUEUE?: Queue         // Queue for email processing
  SENDGRID_API_KEY?: string   // SendGrid API key
  DEFAULT_FROM_EMAIL?: string // Default email sender
  IMAGES_ACCOUNT_ID?: string  // Cloudflare Images account
  IMAGES_API_TOKEN?: string   // Cloudflare Images token
  ENVIRONMENT?: string        // Environment name (dev, staging, prod)
  BUCKET_NAME?: string        // R2 bucket name

  // AI Search bindings (optional)
  AI?: any                    // Workers AI binding
  VECTORIZE_INDEX?: any       // Vectorize index binding
}

Binding Descriptions

BindingRequiredDescription
DBYesCloudflare D1 SQLite database
CACHE_KVYesKV namespace for caching
MEDIA_BUCKETYesR2 bucket for media files
ASSETSYesStatic assets binding
EMAIL_QUEUENoQueue for async email sending
SENDGRID_API_KEYNoAPI key for email sending
DEFAULT_FROM_EMAILNoDefault sender address
AINoWorkers AI for embeddings
VECTORIZE_INDEXNoVectorize for semantic search

Environment Variables

Runtime configuration via environment variables.

Core Variables

VariableDefaultDescription
ENVIRONMENTdevelopmentEnvironment name
JWT_SECRET-Secret for JWT signing
ADMIN_EMAIL-Initial admin email
ADMIN_PASSWORD-Initial admin password

Email Configuration

VariableDefaultDescription
SENDGRID_API_KEY-SendGrid API key
DEFAULT_FROM_EMAIL-Default sender address
DEFAULT_FROM_NAMESonicJSDefault sender name

Media Configuration

VariableDefaultDescription
BUCKET_NAME-R2 bucket name
MAX_FILE_SIZE10485760Max upload size (bytes)
ALLOWED_FILE_TYPESimage/*,video/*,application/pdfAllowed MIME types

Caching Configuration

VariableDefaultDescription
CACHE_ENABLEDtrueEnable caching
CACHE_TTL3600Default cache TTL (seconds)
CACHE_VERSIONv1Cache version for invalidation

AI Search Configuration

VariableDefaultDescription
AI_SEARCH_ENABLEDtrueEnable AI search
VECTORIZE_INDEX_NAMEsonicjs-contentVectorize index name

Collections Config

Configuration for content collections.

Collections Configuration

const app = createSonicJSApp({
  collections: {
    // Directory containing collection definition files
    directory: './src/collections',

    // Automatically sync collection schemas on startup
    autoSync: true
  }
})

Collection File Structure

Collection Definition

// src/collections/blog-posts.ts
import { defineCollection } from '@sonicjs-cms/core'

export default defineCollection({
  name: 'blog_posts',
  displayName: 'Blog Posts',
  description: 'Blog articles and posts',

  // Schema definition
  schema: {
    title: {
      type: 'string',
      required: true,
      maxLength: 200
    },
    slug: {
      type: 'slug',
      from: 'title'
    },
    content: {
      type: 'richtext',
      required: true
    },
    publishedAt: {
      type: 'datetime'
    },
    featured: {
      type: 'boolean',
      default: false
    },
    category: {
      type: 'reference',
      collection: 'categories'
    },
    tags: {
      type: 'array',
      items: { type: 'string' }
    }
  },

  // Workflow settings
  workflow: {
    enabled: true,
    requireApproval: true
  },

  // API settings
  api: {
    enabled: true,
    publicRead: true,
    publicCreate: false
  }
})

Plugin Config

Configuration for SonicJS plugins.

Global Plugin Settings

Plugin Configuration

const app = createSonicJSApp({
  plugins: {
    // Directory for custom plugins
    directory: './src/plugins',

    // Auto-load plugins from directory
    autoLoad: true,

    // Disable all plugins (useful for testing)
    disableAll: false
  }
})

Individual Plugin Settings

Each plugin has its own settings stored in the database:

Plugin Settings Storage

-- Plugin settings are stored in the plugins table
SELECT id, settings FROM plugins WHERE id = 'ai-search';

-- Settings are JSON:
-- {
--   "enabled": true,
--   "ai_mode_enabled": true,
--   "selected_collections": ["1", "2"],
--   "autocomplete_enabled": true,
--   "cache_duration": 1,
--   "results_limit": 20
-- }

Common Plugin Configurations

AI Search Plugin:

SettingTypeDefaultDescription
enabledbooleantrueEnable search
ai_mode_enabledbooleantrueEnable semantic search
selected_collectionsstring[][]Collections to index
autocomplete_enabledbooleantrueEnable suggestions
cache_durationnumber1Cache hours
results_limitnumber20Max results

Turnstile Plugin:

SettingTypeDefaultDescription
siteKeystring-Turnstile site key
secretKeystring-Turnstile secret key
themestringautoWidget theme
sizestringnormalWidget size
enabledbooleanfalseEnable verification

Cache Plugin:

SettingTypeDefaultDescription
memoryEnabledbooleantrueEnable memory cache
kvEnabledbooleanfalseEnable KV cache
defaultTTLnumber3600Default TTL
maxMemorySizenumber50Max memory (MB)

Middleware Config

Configure custom middleware for request processing.

Middleware Execution Order

Request

   ├─▶ Metrics Middleware

   ├─▶ Bootstrap Middleware (migrations, init)

   ├─▶ beforeAuth Middleware (your custom)

   ├─▶ Auth Middleware

   ├─▶ afterAuth Middleware (your custom)

   ├─▶ Route Handler

   └─▶ Response

Middleware Types

Middleware Definition

type Middleware = (
  c: Context,
  next: () => Promise<void>
) => Promise<void>

// Example middleware
const loggingMiddleware: Middleware = async (c, next) => {
  const start = Date.now()
  await next()
  const duration = Date.now() - start
  console.log(`${c.req.method} ${c.req.url} - ${duration}ms`)
}

const authCheckMiddleware: Middleware = async (c, next) => {
  const user = c.get('user')
  if (!user) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  await next()
}

wrangler.toml

Complete example of Cloudflare Worker configuration.

wrangler.toml

name = "my-sonicjs-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

# Environment variables
[vars]
ENVIRONMENT = "production"
DEFAULT_FROM_EMAIL = "noreply@myapp.com"
DEFAULT_FROM_NAME = "My App"
CACHE_ENABLED = "true"
CACHE_TTL = "3600"

# D1 Database
[[d1_databases]]
binding = "DB"
database_name = "my-app-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# KV Namespace for caching
[[kv_namespaces]]
binding = "CACHE_KV"
id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# R2 Bucket for media
[[r2_buckets]]
binding = "MEDIA_BUCKET"
bucket_name = "my-app-media"

# Workers AI (for AI Search)
[ai]
binding = "AI"

# Vectorize (for AI Search)
[[vectorize]]
binding = "VECTORIZE_INDEX"
index_name = "sonicjs-content"

# Queue for email processing (optional)
[[queues.producers]]
queue = "email-queue"
binding = "EMAIL_QUEUE"

# Static assets
[assets]
binding = "ASSETS"
directory = "./public"

# Development environment
[env.development]
[env.development.vars]
ENVIRONMENT = "development"

# Staging environment
[env.staging]
[env.staging.vars]
ENVIRONMENT = "staging"

# Production secrets (set via wrangler secret)
# wrangler secret put JWT_SECRET
# wrangler secret put SENDGRID_API_KEY
# wrangler secret put ADMIN_PASSWORD

Setting Secrets

Set Secrets

# Set JWT secret
npx wrangler secret put JWT_SECRET
# Enter your secret when prompted

# Set SendGrid API key
npx wrangler secret put SENDGRID_API_KEY

# Set initial admin password
npx wrangler secret put ADMIN_PASSWORD

# For specific environment
npx wrangler secret put JWT_SECRET --env production

Request Context Variables

Variables available in request context via c.get() / c.set().

Variables Interface

interface Variables {
  // User information (set by auth middleware)
  user?: {
    userId: string
    email: string
    role: string
    exp: number    // Token expiration
    iat: number    // Token issued at
  }

  // Request metadata
  requestId?: string   // Unique request ID
  startTime?: number   // Request start timestamp
  appVersion?: string  // Application version
}

// Usage in routes
app.get('/api/me', (c) => {
  const user = c.get('user')
  const requestId = c.get('requestId')

  return c.json({
    user,
    requestId,
    version: c.get('appVersion')
  })
})

Next Steps

Was this page helpful?