Most applications I have worked on recently have all run on Boxlang Express, and they're all laid out the same way. That's on purpose. Once one app has a layout that works, every new one starts from it, and I don't have to remember where anything lives.
This post builds a small bookmarks API with that layout and explains why each piece is where it is. Most people are familiar with ColdBox, so I'll point out the ColdBox equivalent as we go. Most of the ideas carry over. The main difference is that boxlang-express does less for you, so you write those parts yourself, and they end up in a file you can read.
What we're building
A JSON API for saved links:
GET /api/bookmarks list
GET /api/bookmarks/:id one
POST /api/bookmarks { url, title, notes? }
PATCH /api/bookmarks/:id { url?, title?, notes? }
DELETE /api/bookmarks/:id
GET /api/health checks the database
It uses MySQL, has no auth, and has no frontend yet. It's small enough to read in one sitting and big enough to need structure.
The layout
server/
server.bxs entry point: settings → services → migrate → build app → listen
start.sh cd to server/ and run server.bxs
.boxlang.json the datasource
.env.example every setting, with its default
services/ domain and infrastructure; never sees req or res
Bootstrap.bx loadSettings() and build(): the whole object graph
Db.bx queryExecute bound to one datasource
Migrator.bx numbered .sql files, applied at startup
ApiError.bx typed errors a route can throw
BookmarkStore.bx the SQL for bookmarks
routes/ HTTP only
Api.bx builds the app: middleware, mounts, error handler
Http.bx request parsing that throws ApiError
BookmarkRoutes.bx the bookmark endpoints
migrations/
001_init.sql
scripts/
add.bxs a CLI task that reuses the same services
tests/specs/
BookmarkSpec.bx
web/ the SPA, when there is one
The layout splits the app into three parts:
- Composition (
Bootstrap, server.bxs) decides which objects exist and how they connect.
- HTTP (
routes/) turns requests into service calls and service results into responses.
- Domain (
services/) does the work and doesn't know HTTP exists.
Everything else follows from keeping those three apart.
Settings: .env and .boxlang.json
BoxLang 1.18+ reads .env and .boxlang.json from the directory it was started in. That's convenient, and it's also the first trap. Start the server from anywhere else and it can't find its datasource. start.sh takes care of that:
#!/usr/bin/env bash
# BoxLang reads .env and .boxlang.json from the working directory
cd "$(dirname "$0")"
exec boxlang server.bxs
The datasource lives in .boxlang.json and reads its values from the environment:
{
"defaultDatasource": "bookmarks",
"datasources": {
"bookmarks": {
"driver": "mysql",
"host": "${env.BOOKMARKS_DB_HOST:127.0.0.1}",
"port": "${env.BOOKMARKS_DB_PORT:3306}",
"database": "${env.BOOKMARKS_DB_NAME:bookmarks}",
"username": "${env.BOOKMARKS_DB_USER:root}",
"password": "${env.BOOKMARKS_DB_PASSWORD}",
"custom": "connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true"
}
}
}
The connection is always UTC, and so is everything stored through it. That saves you from a whole category of bug.
.env.example gets committed. .env doesn't.
# development | production. Development shows real error messages in 500s.
ENV=development
PORT=8080
REQUEST_LOG=true
BOOKMARKS_DB_HOST=127.0.0.1
BOOKMARKS_DB_PORT=3306
BOOKMARKS_DB_NAME=bookmarks
BOOKMARKS_DB_USER=root
BOOKMARKS_DB_PASSWORD=
ColdBox: this is your config/ColdBox.cfc settings plus commandbox-dotenv. The difference is that nothing reads the environment except Bootstrap.loadSettings(), which comes next.
The composition root: Bootstrap.bx
This is the file that does what WireBox does, and it's the one I'd defend hardest.
/**
* Loads settings and wires the services together. Shared by server.bxs, the
* scripts and the tests so they all build the same object graph.
*/
class {
static {
ROOT = expandPath( getDirectoryFromPath( getCurrentTemplatePath() ) & ".." )
}
/** Settings come from the environment only. `overrides` replaces whole sections (tests use it). */
static struct function loadSettings( struct overrides = {} ) {
var environment = lcase( setting( "ENV", "development" ) )
var settings = {
datasource : "bookmarks",
server : {
port : int( setting( "PORT", 8080 ) ),
environment : environment,
production : environment == "production",
requestLog : flag( "REQUEST_LOG", true )
}
}
return settings.append( arguments.overrides )
}
static struct function build( required struct settings ) {
var db = new Db( arguments.settings.datasource )
return {
settings : arguments.settings,
db : db,
migrator : new Migrator( db, static.ROOT & "/migrations" ),
bookmarks : new BookmarkStore( db )
}
}
private static string function setting( required string name, defaultValue = "" ) {
var value = trim( getSystemSetting( arguments.name, "" ) )
return len( value ) ? value : arguments.defaultValue
}
/** "true"/"1" and "false"/"0" exactly; anything else is the default. */
private static boolean function flag( required string name, required boolean defaultValue ) {
var value = lcase( setting( arguments.name, "" ) )
if ( compare( value, "true" ) == 0 || compare( value, "1" ) == 0 ) {
return true
}
if ( compare( value, "false" ) == 0 || compare( value, "0" ) == 0 ) {
return false
}
return arguments.defaultValue
}
}
Three things are going on here:
- Constructor injection, by hand.
new BookmarkStore( db ). There's no container, no property inject=, no mappings DSL. The object graph is the return value of one function.
- One plain struct out.
svc is a struct of services. Routes, scripts and tests all receive the same struct.
- Exact booleans. BoxLang will happily tell you
"yes" == "true". flag() uses compare() so REQUEST_LOG=yes means "use the default", not "on". That sounds pedantic until it bites you on a security flag.
ColdBox: Bootstrap.build() is config/WireBox.cfc with the magic removed. WireBox earns its keep in a big ColdBox app with modules contributing mappings. In a BoxExpress app the whole graph fits on a screen (Feedhouse's is about 120 lines for 60-odd services), and a circular dependency becomes a line you can see instead of a stack trace.
The cost is real, though. Every new service needs a line here, and the order of the lines matters. I think that's a fair trade. Your mileage will vary with team size.
Database plumbing: Db.bx and Migrator.bx
Db is a thin wrapper so a store never has to know which datasource it's talking to:
/**
* Runs queries against one datasource: a name from .boxlang.json, or an
* inline struct (the tests' database).
*/
class {
property name="datasource";
function init( required datasource ) {
variables.datasource = arguments.datasource
return this
}
function query( required string sql, any params = {}, struct options = {} ) {
return queryExecute( arguments.sql, arguments.params, { datasource: variables.datasource }.append( arguments.options ) )
}
function execute( required string sql, any params = {} ) {
var result = {}
queryExecute( arguments.sql, arguments.params, { datasource: variables.datasource, result: "result" } )
return result
}
}
Because the datasource can be an inline struct, the tests can point the whole app at a bookmarks_test database with no changes to .boxlang.json.
Migrator applies migrations/NNN_name.sql in order and records the highest version applied:
/** Applies numbered .sql files (001_name.sql, …) in order; schema_version keeps the highest applied. */
class {
function init( required db, required string directory ) {
variables.db = arguments.db
variables.directory = arguments.directory
return this
}
array function run() {
variables.db.execute( "CREATE TABLE IF NOT EXISTS schema_version ( version INT NOT NULL PRIMARY KEY, applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP )" )
var current = currentVersion()
var applied = []
var files = directoryList( variables.directory, false, "name", "*.sql", "name" )
.filter( ( name ) => reFind( "^\d+_", name ) && val( listFirst( name, "_" ) ) > current )
.sort( ( a, b ) => val( listFirst( a, "_" ) ) - val( listFirst( b, "_" ) ) )
for ( var name in files ) {
// one statement per execute; naive, but fine for hand-written migrations
for ( var statement in listToArray( fileRead( variables.directory & "/" & name ), ";" ) ) {
if ( len( trim( statement ) ) ) {
variables.db.execute( trim( statement ) )
}
}
variables.db.execute( "INSERT INTO schema_version ( version ) VALUES ( ? )", [ val( listFirst( name, "_" ) ) ] )
applied.append( name )
}
return applied
}
numeric function currentVersion() {
return variables.db.query( "SELECT COALESCE( MAX( version ), 0 ) AS v FROM schema_version" ).v
}
}
The first migration:
-- migrations/001_init.sql
CREATE TABLE bookmarks (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(2048) NOT NULL,
url_hash CHAR(64) AS ( SHA2( url, 256 ) ) STORED,
title VARCHAR(255) NOT NULL,
notes TEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_bookmarks_url_hash ( url_hash )
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
A 2048-character URL is too long for a utf8mb4 unique index, so the index goes on a hash column that MySQL generates itself.
MySQL commits DDL as it goes, so a migration that fails halfway is not rolled back. Fix it and rerun. Feedhouse's version also recognizes "this column already exists" errors and skips them, which makes a half-applied migration safe to rerun. That's worth adding once you've had a deploy killed mid-ALTER.
ColdBox: this is cfmigrations without the CFC-per-migration layer or the CommandBox dependency. It runs on every startup, so a deploy is just "start the new version".
The domain: BookmarkStore.bx
One class per aggregate. All the SQL for bookmarks lives here, and it returns plain structs and arrays.
/**
* Saved links. All bookmark SQL is here; results are plain structs and arrays,
* which is what res.json() can serialize.
*/
class {
property name="db";
static {
COLUMNS = "id, url, title, COALESCE( notes, '' ) AS notes, DATE_FORMAT( created_at, '%Y-%m-%dT%H:%i:%sZ' ) AS createdAt"
}
function init( required db ) {
variables.db = arguments.db
return this
}
array function list() {
return variables.db.query( "SELECT #static.COLUMNS# FROM bookmarks ORDER BY id DESC", [], { returnType: "array" } )
}
struct function get( required numeric id ) {
var rows = variables.db.query( "SELECT #static.COLUMNS# FROM bookmarks WHERE id = ?", [ arguments.id ], { returnType: "array" } )
return rows.len() ? rows[ 1 ] : {}
}
struct function findByUrl( required string link ) {
var rows = variables.db.query(
"SELECT #static.COLUMNS# FROM bookmarks WHERE url_hash = SHA2( ?, 256 )",
[ arguments.link ],
{ returnType: "array" }
)
return rows.len() ? rows[ 1 ] : {}
}
struct function create( required string link, required string title, string notes = "" ) {
var result = variables.db.execute(
"INSERT INTO bookmarks ( url, title, notes ) VALUES ( ?, ?, ? )",
[ arguments.link, arguments.title, arguments.notes ]
)
return get( result.generatedKey )
}
/** `changes` holds any of url, title, notes; missing keys are left alone. */
struct function update( required numeric id, required struct changes ) {
var sets = []
var params = []
for ( var column in [ "url", "title", "notes" ] ) {
if ( arguments.changes.keyExists( column ) ) {
sets.append( "#column# = ?" )
params.append( arguments.changes[ column ] )
}
}
if ( sets.len() ) {
params.append( arguments.id )
variables.db.execute( "UPDATE bookmarks SET #sets.toList( ', ' )# WHERE id = ?", params )
}
return get( arguments.id )
}
boolean function delete( required numeric id ) {
return variables.db.execute( "DELETE FROM bookmarks WHERE id = ?", [ arguments.id ] ).recordCount > 0
}
}
A few things to note:
- It doesn't know about HTTP. It never throws a 404. "Not found" comes back as an empty struct, and the route decides what that means.
link, not url. url is a scope name in BoxLang. A variable or argument named url silently shadows it. Same goes for form, session, request, server and friends.
- Plain data out.
res.json() only serializes real structs and arrays. A class instance comes out as {}, with no error. Returning query rows as arrays of structs avoids that entirely.
- Dates formatted in SQL. The connection is UTC, so
createdAt leaves as an ISO string with a Z, and the client doesn't have to guess.
ColdBox: this is your models/BookmarkService.cfc. If you use Quick or qb you'd write less SQL. I like seeing the query, and a store per aggregate keeps any one file from turning into a 3,000-line service.
Errors you throw: ApiError.bx
Route handlers never build error responses. They throw a typed error, and one handler at the end of the chain turns it into JSON.
/** Errors a route can throw; the error handler maps the type to a status. */
class {
static {
STATUS = {
"Api.BadRequest" : 400,
"Api.NotFound" : 404,
"Api.Conflict" : 409
}
}
static function badRequest( required string message ) {
throw( type = "Api.BadRequest", message = arguments.message )
}
static function notFound( string message = "Not found" ) {
throw( type = "Api.NotFound", message = arguments.message )
}
/** `extra` is merged into the response body: { bookmarkId } on a duplicate. */
static function conflict( required string message, struct extra = {} ) {
throw( type = "Api.Conflict", message = arguments.message, extendedInfo = jsonSerialize( arguments.extra ) )
}
static numeric function statusFor( required string type ) {
return static.STATUS[ arguments.type ] ?: 500
}
static string function codeFor( required numeric status ) {
switch ( arguments.status ) {
case 400: return "bad_request"
case 404: return "not_found"
case 409: return "conflict"
default : return "server_error"
}
}
}
Because a throw stops the handler, there's no if ( !found ) { return res.status( 404 )... } dance. Handlers read top to bottom and the unhappy paths take care of themselves.
ColdBox: this is the ColdBox REST pattern of throwing and letting onError or onException in your base handler call event.renderData( statusCode = … ), except here it's one function, and it's the only place an error response gets built.
Request parsing: Http.bx
Validation helpers that either return a clean value or throw. That's the whole trick.
import services.ApiError;
/** Request parsing shared by the route files. Each helper throws rather than returning a sentinel. */
class {
/** A path id that isn't a positive integer can't name anything: 404, not 400. */
static numeric function pathId( required struct params, string name = "id" ) {
var raw = arguments.params[ arguments.name ] ?: ""
if ( !reFind( "^[1-9][0-9]{0,9}$", raw ) ) {
ApiError::notFound()
}
return raw
}
static struct function body( required req ) {
var payload = arguments.req.body ?: {}
if ( !isStruct( payload ) ) {
ApiError::badRequest( "Expected a JSON object" )
}
return payload
}
static string function requiredString( required struct payload, required string name, numeric maxLength = 1024 ) {
var raw = arguments.payload[ arguments.name ] ?: ""
if ( !isSimpleValue( raw ) || !len( trim( raw ) ) ) {
ApiError::badRequest( "#arguments.name# is required" )
}
if ( len( trim( raw ) ) > arguments.maxLength ) {
ApiError::badRequest( "#arguments.name# is longer than #arguments.maxLength# characters" )
}
return trim( raw )
}
/** "" when absent or null. */
static string function optionalString( required struct payload, required string name, numeric maxLength = 1024 ) {
var raw = arguments.payload[ arguments.name ] ?: ""
if ( !isSimpleValue( raw ) ) {
ApiError::badRequest( "#arguments.name# must be a string" )
}
if ( len( trim( raw ) ) > arguments.maxLength ) {
ApiError::badRequest( "#arguments.name# is longer than #arguments.maxLength# characters" )
}
return trim( raw )
}
static string function requiredUrl( required struct payload, required string name ) {
var link = requiredString( arguments.payload, arguments.name, 2048 )
if ( !reFindNoCase( "^https?://[^\s/]+", link ) ) {
ApiError::badRequest( "#arguments.name# must be an http or https URL" )
}
return link
}
}
ColdBox: this does the job of cbvalidation constraints. It's less declarative and has fewer moving parts. Each rule is a function you can step into.
The endpoints: BookmarkRoutes.bx
One file per resource. It's a class with a single static register( router, svc ).
import services.ApiError;
import routes.Http;
class {
static void function register( required router, required struct svc ) {
// captured up front: the handlers below are closures and run long after register() returns
var bookmarks = arguments.svc.bookmarks
var requireBookmark = ( id ) => {
var bookmark = bookmarks.get( id )
if ( bookmark.isEmpty() ) {
ApiError::notFound( "Bookmark not found" )
}
return bookmark
}
var requireUniqueUrl = ( link, exceptId ) => {
var existing = bookmarks.findByUrl( link )
if ( !existing.isEmpty() && existing.id != exceptId ) {
ApiError::conflict( "That URL is already saved", { bookmarkId: existing.id } )
}
}
arguments.router.get( "/bookmarks", ( req, res ) => res.json( bookmarks.list() ) )
arguments.router.get( "/bookmarks/:id", ( req, res ) => {
res.json( requireBookmark( Http::pathId( req.params ) ) )
} )
/** { url, title, notes? } */
arguments.router.post( "/bookmarks", ( req, res ) => {
var payload = Http::body( req )
var link = Http::requiredUrl( payload, "url" )
var title = Http::requiredString( payload, "title", 255 )
var notes = Http::optionalString( payload, "notes", 2000 )
requireUniqueUrl( link, 0 )
res.status( 201 ).json( bookmarks.create( link, title, notes ) )
} )
/** { url?, title?, notes? } */
arguments.router.patch( "/bookmarks/:id", ( req, res ) => {
var id = Http::pathId( req.params )
var payload = Http::body( req )
requireBookmark( id )
var changes = {}
if ( payload.keyExists( "url" ) ) {
changes.url = Http::requiredUrl( payload, "url" )
requireUniqueUrl( changes.url, id )
}
if ( payload.keyExists( "title" ) ) {
changes.title = Http::requiredString( payload, "title", 255 )
}
if ( payload.keyExists( "notes" ) ) {
changes.notes = Http::optionalString( payload, "notes", 2000 )
}
res.json( bookmarks.update( id, changes ) )
} )
arguments.router.delete( "/bookmarks/:id", ( req, res ) => {
if ( !bookmarks.delete( Http::pathId( req.params ) ) ) {
ApiError::notFound( "Bookmark not found" )
}
res.status( 204 ).end()
} )
}
}
Every handler follows the same order: parse with Http::, check with a require… guard, call the store, send JSON. If a handler grows past that, the extra logic belongs in a service.
Two things specific to BoxLang:
- Capture services into local
vars before defining closures. The closures don't see register()'s arguments scope reliably, so pull what you need into locals first.
- Qualify static calls (
Http::pathId, ApiError::notFound). A closure inside a static function can't call sibling statics by bare name.
The routes are static because they hold no state. There's nothing to instantiate, so there's no instance to forget to wire.
ColdBox: this is a handler, handlers/Bookmarks.cfc, with index, show, create, update and delete actions. ( req, res ) plays the role of ( event, rc, prc ). The routes are declared next to the code that handles them instead of in config/Router.cfc, which I prefer, since you never have to open two files to see what PATCH /bookmarks/:id does.
Putting the app together: Api.bx
Api.build( svc ) returns a configured app without calling listen(). The server and the tests both build it the same way.
import services.ApiError;
/**
* /health open; touches nothing, so a database blip doesn't fail the process
* /api/health checks the database
* /api/bookmarks* the bookmarks API
* /api/* anything else is a JSON 404, not the SPA
*/
class {
static function build( required struct svc ) {
var settings = arguments.svc.settings
var app = boxExpress()
app.set( "env", settings.server.environment )
app.set( "log", settings.server.requestLog )
app.use( boxExpressHelmet() )
app.get( "/health", ( req, res ) => res.send( "ok" ) )
var db = arguments.svc.db
var migrator = arguments.svc.migrator
app.get( "/api/health", ( req, res ) => {
try {
db.query( "SELECT 1" )
res.json( { status: "ok", schemaVersion: migrator.currentVersion() } )
} catch ( any e ) {
res.status( 503 ).json( { error: true, code: "unavailable", message: "Database unavailable" } )
}
} )
var api = boxExpressRouter()
api.use( boxExpressJSON() )
BookmarkRoutes::register( api, arguments.svc )
app.use( "/api", api )
app.all( "/api/*", ( req, res ) => {
ApiError::notFound( "No such endpoint: #req.method# #req.path#" )
} )
// four parameters makes it an error handler; registered last
app.use( errorHandler( settings.server.environment == "development" ) )
return app
}
/** Every error leaves as { error: true, code, message }. */
private static function errorHandler( required boolean development ) {
var showInternals = arguments.development
return ( err, req, res, next ) => {
var type = err.type ?: ""
var status = ApiError::statusFor( type )
var payload = { error: true, code: ApiError::codeFor( status ), message: err.message ?: "Error" }
if ( status == 409 && len( err.extendedInfo ?: "" ) ) {
payload.append( jsonDeserialize( err.extendedInfo ) )
}
if ( status == 500 ) {
println( "[api] #req.method# #req.path# failed: #type# #payload.message#" )
payload.message = showInternals ? payload.message : "Internal Server Error"
}
res.status( status ).json( payload )
}
}
}
The comment block at the top is the map of the app. In Feedhouse it lists every prefix and what guards it (open, bearer token, session plus CSRF, login, admin), and the code below it is registered in exactly that order. Middleware in BoxExpress runs in registration order, so the order is the security model. Making that order readable in one place is the point of Api.bx.
ColdBox: Api.bx is config/Router.cfc plus the interceptors you'd register in ColdBox.cfc. api.use( boxExpressJSON() ) is a preProcess interceptor scoped to a route group. A requireLogin middleware is what cbsecurity's rules do for you. Here it's a function you mount, and anything registered after it is protected.
The entry point: server.bxs
With everything else in place, the entry point is short:
/**
* boxlang server.bxs (run from server/, or use start.sh)
*/
import services.Bootstrap;
import routes.Api;
settings = Bootstrap::loadSettings()
svc = Bootstrap::build( settings )
applied = svc.migrator.run()
if ( applied.len() ) {
println( "Applied migrations: #applied.toList( ', ' )#" )
}
app = Api::build( svc )
// background work goes here: app.schedule( "5 * * * *", () => …, { name: "…", timezone: "UTC" } )
app.listen( settings.server.port, ( port ) => {
println( "Bookmarks listening on http://localhost:#port#" )
} )
listen() blocks. Anything after it doesn't run until shutdown, which catches out everyone coming from Node.
Scheduled jobs go between build and listen. BoxExpress takes intervals or cron expressions now. The scheduler is in-memory, so a job that must run once a day should record its last run in the database. Otherwise a restart at the wrong moment either skips it or runs it twice.
ColdBox: this file covers Application.cfc, the ColdBox bootstrap and config/Scheduler.cfc. There's no onApplicationStart and no framework reinit. The process starts, builds the graph once and serves.
Scripts reuse the same graph
Because Bootstrap is the only place the app is wired, a CLI task gets the real services for free:
/**
* boxlang scripts/add.bxs <url> <title> (run from server/)
*/
import services.Bootstrap;
cli = cliGetArgs()
if ( cli.positionals.len() < 2 ) {
println( "Usage: boxlang scripts/add.bxs <url> <title>" )
createObject( "java", "java.lang.System" ).exit( 1 )
}
svc = Bootstrap::build( Bootstrap::loadSettings() )
svc.migrator.run()
link = cli.positionals[ 1 ]
title = cli.positionals[ 2 ]
existing = svc.bookmarks.findByUrl( link )
if ( !existing.isEmpty() ) {
println( "Already saved as ##" & existing.id )
} else {
println( "Saved as ##" & svc.bookmarks.create( link, title ).id )
}
It doesn't go through HTTP and doesn't duplicate any logic. It calls the same store the API calls. The script skips the API's URL validation, though, so anything that must hold no matter how data gets in belongs in the store, not in Http.
ColdBox: CommandBox task runners, minus the need to boot ColdBox inside one to reach your models.
Tests
The tests use the same graph with one override: the datasource.
import services.Bootstrap;
import routes.Api;
class extends="testbox.system.BaseSpec" {
function beforeAll() {
variables.svc = Bootstrap::build( Bootstrap::loadSettings( {
datasource : {
driver : "mysql",
host : getSystemSetting( "BOOKMARKS_DB_HOST", "127.0.0.1" ),
port : getSystemSetting( "BOOKMARKS_DB_PORT", "3306" ),
database : "bookmarks_test",
username : getSystemSetting( "BOOKMARKS_DB_USER", "root" ),
password : getSystemSetting( "BOOKMARKS_DB_PASSWORD", "" ),
custom : "connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true"
},
server : { port: 0, environment: "test", production: false, requestLog: false }
} ) )
variables.svc.migrator.run()
variables.app = Api::build( variables.svc )
}
function run() {
describe( "Bookmarks", () => {
beforeEach( () => svc.db.execute( "DELETE FROM bookmarks" ) )
it( "creates one and reads it back", () => {
var created = app.inject( { method: "POST", url: "/api/bookmarks", body: { url: "https://boxlang.io", title: "BoxLang" } } )
expect( created.statusCode ).toBe( 201 )
var fetched = app.inject( "/api/bookmarks/#created.json().id#" )
expect( fetched.json().title ).toBe( "BoxLang" )
} )
it( "refuses a duplicate URL and says which one it is", () => {
var first = app.inject( { method: "POST", url: "/api/bookmarks", body: { url: "https://boxlang.io", title: "One" } } )
var again = app.inject( { method: "POST", url: "/api/bookmarks", body: { url: "https://boxlang.io", title: "Two" } } )
expect( again.statusCode ).toBe( 409 )
expect( again.json().bookmarkId ).toBe( first.json().id )
} )
it( "answers a bad id with a 404, not a 500", () => {
expect( app.inject( "/api/bookmarks/nope" ).statusCode ).toBe( 404 )
expect( app.inject( "/api/bookmarks/999999" ).json().code ).toBe( "not_found" )
} )
it( "returns JSON for an unknown endpoint", () => {
expect( app.inject( "/api/nothing-here" ).json().code ).toBe( "not_found" )
} )
} )
}
}
app.inject() runs a request through the real router, middleware and error handler without opening a port. Feedhouse's older specs use listen( port = N, options = { block: false } ) and a real HTTP client, which you still need for WebSockets and anything that touches req.rawExchange(). For a JSON API, inject() is enough and a lot faster.
ColdBox: this is BaseTestCase with execute( route = "/api/bookmarks", … ), minus the virtual-app setup and reset() between specs. The app is an object you built, so you build another one if you need it.
The ColdBox map
| ColdBox | BoxExpress app | Notes |
Application.cfc + bootstrap | server.bxs | Starts once, no reinit |
config/ColdBox.cfc settings | Bootstrap.loadSettings() | Only reads the environment |
config/WireBox.cfc / inject= | Bootstrap.build() | Constructor injection by hand |
config/Router.cfc | routes/Api.bx + register() | Routes live next to their handlers |
handlers/Bookmarks.cfc | routes/BookmarkRoutes.bx | ( req, res ) instead of ( event, rc, prc ) |
models/ | services/ | Never sees req or res |
Interceptors (preProcess) | app.use() / router.use() | Order of registration is order of execution |
| cbsecurity rules | A requireLogin middleware mounted on a router | Everything after it is protected |
| cbvalidation | routes/Http.bx | Throw or return a clean value |
onError / onException | One 4-arg error handler | The only place error JSON is built |
| cfmigrations | Migrator.bx + migrations/*.sql | Runs at startup |
config/Scheduler.cfc | app.schedule() | In-memory; persist last-run for daily jobs |
| CommandBox task runners | scripts/*.bxs | Same Bootstrap, no framework boot |
BaseTestCase + execute() | app.inject() | No port, no virtual app |
| CBWIRE | No equivalent | Use a SPA in web/ |
Why lay it out like this
The short version: every way into the app (server, script, test) builds the same object graph from the same function, and nothing below the HTTP layer knows HTTP exists.
That gets you a few things:
- Tests are cheap. Swap the datasource, build, inject. There's no framework to boot.
- Scripts are free. Any job you'd otherwise hide behind an admin endpoint can be a ten-line
.bxs.
- The security model is one file.
Api.bx reads top to bottom in the order requests are checked.
- Handlers stay boring. Parse, check, call, respond. Anything interesting is in a service where it can be tested without HTTP.
- Nothing is magic. When something breaks, the stack trace goes through code you wrote, which is a mixed blessing, but it is at least your code.
And here's what it costs:
- Boilerplate you'd otherwise get for free.
Http.bx, ApiError.bx and Migrator.bx get copied into every new app. They should probably be a module. I haven't done that yet because they still change slightly with each app, which is a weak excuse.
Bootstrap.build() grows. Feedhouse's is 120 lines. It's still one file you can read, but at some point a container starts to make sense again. I haven't hit that point.
- No conventions to lean on. ColdBox finds your handler by name. Here you register it. A new developer has to read
Api.bx first. I consider that a feature. They may not.
Scaffolding it with Claude
Copying Http.bx, ApiError.bx, Db.bx and Migrator.bx by hand gets old by the third app. So the layout, along with every BoxExpress and BoxLang trap that has cost me an afternoon, is written up as a Claude skill. A skill is a SKILL.md that Claude loads when a task matches its description. Ask it for a BoxExpress app and it starts from this layout instead of inventing one, and it already knows that listen() blocks and that url is a scope.
The whole skill is in the appendix at the end of this post. To install it:
- Claude Code: save it as
~/.claude/skills/boxexpress/SKILL.md to use it in every project, or as .claude/skills/boxexpress/SKILL.md inside a repo to commit it for that project.
- The Claude apps: put
SKILL.md in a folder named boxexpress, zip the folder, and upload it as a custom skill in Claude's settings.
Then ask for what you want, and be specific about scope:
Scaffold a BoxExpress app in ./bookmarks: a JSON API for saved links
(url, title, notes) on MySQL. Use the house layout from the boxexpress skill.
Include migrations, a scripts/add.bxs task and app.inject() specs.
No auth and no frontend yet.
You get the tree from this post, wired up, with the error handler in place and specs that run. Leaving out auth matters. Ask for "an app" and you'll get sessions, CSRF and a login flow you didn't want yet.
A few caveats:
- It's a snapshot. This copy tracks BoxExpress 0.2.29. The skill tells Claude the repo is the authority and to check
CHANGELOG.md before trusting its own notes, but a skill can't update itself. When BoxExpress changes a default, update the skill too.
- It encodes my preferences. Hand-wired
Bootstrap, raw SQL in stores and static route modules are choices, not laws. If you want qb, edit the skill. That's the point of having it in a file.
- Review what it writes. Treat the output like a pull request from someone who has read the docs carefully but has never run your app. It's usually right about the framework and sometimes wrong about your data.
Next
The obvious additions, in the order Feedhouse grew them:
- A SPA in
web/. Vite builds to web/dist. Api.bx serves /assets with a one-year cache and index.html with no-cache, and registers app.get( "/*", sendIndex ) as the fallback. In development, Vite proxies /api to :8080.
- Sessions and CSRF. A
SessionStore service backed by MySQL, api.use( sessions, boxExpressJSON(), boxExpressCsrf() ), then a requireLogin middleware that sets req.user. Open routes go above it, account routes below.
- A Dockerfile. Two stages: Node builds the SPA, then
ortussolutions/boxlang:cli with install-bx-module boxlang-express@<version> bx-mysql@<version> --local, with versions pinned. No CommandBox at runtime.
Appendix
The boxexpress skill can be found here.
Wrapping Up
None of this is clever, and that’s the point. ColdBox gave us conventions so we never had to decide where things go. BoxExpress gives you none, so you decide once and write it down. This post is what I wrote down: one function that builds the app, routes that only speak HTTP, services that don’t know HTTP exists, and errors you throw instead of build.
Four apps in, I haven’t had to go looking for anything, which is about the best review a layout can get.
If you build something with it, or find where it falls apart, I’d like to hear about it. The skill in the appendix will get you a running skeleton in a few minutes. The layout itself takes one app to get used to.
No comments yet — be the first.