BoxLang Express is deliberately shaped like Express.js: routes are functions that take req and res. That suits people coming from Node. It is less comfortable if you have spent years writing ColdBox, where a request lands in a handler, rc holds the input, prc holds what the view needs, and the view and layout are found by convention.
boxlang-express-mvc is a small module that puts that shape on top of BoxExpress. You get function index( event, rc, prc ), a config/Router.bx with route().to(), and views/ and layouts/ folders that work the way you expect.
The goal is familiar, not compatible. It will not run an existing ColdBox app, ColdBox modules or CBWIRE. What it does is let a ColdBox developer read a BoxExpress app and know where everything is. Underneath, every route it registers is an ordinary BoxExpress route, built once when the app starts.
This post builds a todo list with it, one file at a time, and points out what is the same as ColdBox and what is not. The finished app is in the repo under examples/todo.
Step 1: install
Make a folder for the app and install the modules into it:
mkdir todo && cd todo
install-bx-module boxlang-express boxlang-express-mvc bx-esapi --local
--local puts them in boxlang_modules/ beside your code. BoxLang finds modules relative to the directory you start it from, so always run the app from this folder.
This is the layout we are going to end up with:
todo/
server.bxs
boxlang_modules/
config/Router.bx
handlers/todos.bx
models/TodoService.bx
layouts/Main.bxm
views/todos/index.bxm
views/todos/item.bxm
views/todos/edit.bxm
ColdBox similarity: the folder names are the ones you know: config, handlers, models, layouts, views. Nothing forces those names (each is a path you pass in), but there is no reason to pick others.
Step 2: the model
The todo list lives in memory. This is the one file with nothing ColdBox about it, and the one where the main difference from ColdBox shows up.
// models/TodoService.bx
class {
function init() {
variables.todos = createObject( "java", "java.util.concurrent.ConcurrentHashMap" ).init()
variables.nextId = createObject( "java", "java.util.concurrent.atomic.AtomicInteger" ).init( 0 )
add( "Read the README" )
add( "Write a handler" )
toggle( 1 )
return this
}
function list( filter = "all" ) {
var all = []
for ( var key in variables.todos.keySet().toArray() ) {
var todo = variables.todos.get( key )
if ( filter == "all" || ( filter == "done" ) == todo.done ) {
all.append( todo )
}
}
return all.sort( ( a, b ) => a.id - b.id )
}
function get( id ) {
if ( !isValid( "integer", id ) ) {
return {}
}
return variables.todos.get( javacast( "int", id ) ) ?: {}
}
function counts() {
var all = list()
var done = all.filter( ( todo ) => todo.done ).len()
return { all: all.len(), done: done, active: all.len() - done }
}
function add( title ) {
var id = variables.nextId.incrementAndGet()
variables.todos.put( javacast( "int", id ), { id: id, title: title, done: false } )
return id
}
function rename( id, title ) {
variables.todos.computeIfPresent( javacast( "int", id ), ( key, todo ) => { return { id: todo.id, title: title, done: todo.done } } )
}
function toggle( id ) {
variables.todos.computeIfPresent( javacast( "int", id ), ( key, todo ) => { return { id: todo.id, title: todo.title, done: !todo.done } } )
}
function remove( id ) {
variables.todos.remove( javacast( "int", id ) )
}
function clearCompleted() {
for ( var todo in list( "done" ) ) {
remove( todo.id )
}
}
}
Why the ConcurrentHashMap and the AtomicInteger? BoxExpress gives every request its own thread, and there is one TodoService for all of them. Two people adding a todo at the same moment are two threads inside add() at once. A plain struct and id++ would mostly work and occasionally lose a todo.
ColdBox similarity: this is a singleton model, the same as component singleton in WireBox. Singletons have always needed to be thread-safe in ColdBox too. The difference is that here nothing else is in the way, so you notice sooner.
Step 3: the entry point
// server.bxs
app = boxExpress()
app.set( "env", getSystemSetting( "APP_ENV", "production" ) )
app.set( "reloadOnChange", app.getSetting( "env" ) == "development" )
app.use( boxExpressSession( { saveUninitialized: false } ) )
app.use( boxExpressUrlencoded() )
app.use( boxExpressCsrf() )
svc = { todoService: new models.TodoService() }
mvc = boxExpressMvc( {
handlers: expandPath( "./handlers" ),
views: expandPath( "./views" ),
layouts: expandPath( "./layouts" ),
routes: expandPath( "./config/Router.bx" ),
services: svc
} )
app.use( mvc.router() )
app.use( ( req, res, next ) => res.status( 404 ).send( "Page not found" ) )
app.use( ( err, req, res, next ) => {
println( "Error on #req.method# #req.originalUrl#: #err.message#" )
res.status( 500 ).send( "Something went wrong." )
} )
app.listen( getSystemSetting( "PORT", 3000 ), ( port ) => println( "http://localhost:#port#" ) )
Four things are happening:
boxExpressUrlencoded() is BoxExpress middleware that parses form posts. Without it there is no form data to put in rc.
boxExpressSession() and boxExpressCsrf() are BoxExpress middleware too. Together they reject any POST that doesn't carry the token stored in the visitor's session, with a 403, before a handler sees it. The order matters: session, then the form parser, then the check.
boxExpressMvc() scans handlers/, creates one instance of each handler, runs the routes file and registers everything. If a route points at a handler or action that doesn't exist, it throws here, at startup, and names the route.
mvc.router() hands back a plain BoxExpress router, mounted like any other. Middleware in front of it, the 404 after it and the error handler at the end are all ordinary BoxExpress.
ColdBox similarity: server.bxs does the jobs of Application.cfc, index.cfm and config/ColdBox.cfc. The last app.use() is your onException, and the one before it is invalidEventHandler. The session and CSRF lines stand in for cbcsrf.
Different from ColdBox: there is no servlet container and no application scope. boxlang server.bxs starts a process that listens on a port, and this script is the whole of its startup.
Step 4: routes
// config/Router.bx
class {
function configure() {
route( "/" ).withAction( { GET: "index", POST: "create" } ).toHandler( "todos" )
route( "/clear" ).withAction( { POST: "clearCompleted" } ).toHandler( "todos" )
route( "/todos/:id(\d+)" ).withAction( { GET: "edit", POST: "update" } ).toHandler( "todos" )
route( "/todos/:id(\d+)/toggle" ).withAction( { POST: "toggle" } ).toHandler( "todos" )
route( "/todos/:id(\d+)/delete" ).withAction( { POST: "delete" } ).toHandler( "todos" )
route( "/api/todos" ).withAction( { GET: "data" } ).toHandler( "todos" )
route( "/healthcheck", ( req, res ) => res.send( "Ok!" ) )
}
}
ColdBox similarity: this is the ColdBox router DSL. route(), withAction(), toHandler(), to(), as() and resources() all read the way they do in Router.cfc, inside the same configure() function. The conventions route, route( "/:handler/:action?" ).end(), is available too.
A few things to notice:
withAction() ties HTTP methods to actions. Everything that changes data is POST only, so a GET to /todos/2/toggle is a 404. With plain route( "/x" ).to( "todos.toggle" ), every method would reach the action, as in ColdBox.
:id(\d+) is a BoxExpress path constraint. /todos/abc doesn't match the route at all, so it is a 404 before any handler runs.
- The last route is a plain BoxExpress function. Any route can skip the MVC layer entirely.
Different from ColdBox: I left the conventions route out on purpose. It answers every HTTP method, which would make GET /todos/delete reachable. It is opt-in for that reason. Browsers also can't send PUT or DELETE from a form and there is no built-in _method override, which is why this app uses explicit POST routes and not resources( "todos" ).
Step 5: the handler
// handlers/todos.bx
class {
property name="todoService";
function preHandler( event, rc, prc, action ) {
if ( listFindNoCase( "edit,update,toggle,delete", action ) ) {
prc.todo = todoService.get( rc.id )
if ( prc.todo.isEmpty() ) {
event.renderData( type = "text", data = "No such todo", statusCode = 404 )
}
}
}
function index( event, rc, prc ) {
prc.filter = listFindNoCase( "active,done", event.getValue( "filter", "all" ) ) ? lCase( rc.filter ) : "all"
prc.todos = todoService.list( prc.filter )
prc.counts = todoService.counts()
prc.title = "Todos"
}
function create( event, rc, prc ) {
var title = _cleanTitle( rc )
if ( !len( title ) ) {
return event.relocate( "todos.index", "error=title" )
}
todoService.add( title )
event.relocate( "todos.index" )
}
function edit( event, rc, prc ) {
prc.title = "Edit todo"
}
function update( event, rc, prc ) {
var title = _cleanTitle( rc )
if ( !len( title ) ) {
return event.relocate( event.buildLink( "todos.edit", { id: prc.todo.id, error: "title" } ) )
}
todoService.rename( prc.todo.id, title )
event.relocate( "todos.index" )
}
function toggle( event, rc, prc ) {
todoService.toggle( prc.todo.id )
event.relocate( "todos.index" )
}
function delete( event, rc, prc ) {
todoService.remove( prc.todo.id )
event.relocate( "todos.index" )
}
function clearCompleted( event, rc, prc ) {
todoService.clearCompleted()
event.relocate( "todos.index" )
}
function data( event, rc, prc ) {
event.renderData( type = "json", data = todoService.list( "all" ) )
}
private function _cleanTitle( rc ) {
var title = rc.title ?: ""
return isSimpleValue( title ) ? trim( title ).mid( 1, 200 ) : ""
}
}
ColdBox similarity: almost all of it.
- The action signature is
( event, rc, prc ).
rc is the request collection: query string, form fields and route params merged. prc is the private collection the view reads.
event.getValue( "filter", "all" ), event.renderData(), event.relocate( "todos.index" ) and event.buildLink() carry their ColdBox names.
index and edit never mention a view. The implicit view is views/todos/index.bxm and views/todos/edit.bxm, by convention.
preHandler runs before every action, with the action name as its fourth argument.
property name="todoService"; is filled in for you.
Different from ColdBox:
preHandler can stop the request. If it sends a response, the action doesn't run. Here it loads the todo for the four actions that need one and answers 404 itself when there isn't one, so those actions can assume prc.todo exists. In ColdBox you would reach for event.overrideEvent() or an interceptor.
renderData() and relocate() send immediately. ColdBox waits until the end of the request. Here the response has gone by the time the call returns, which is why the validation branches return straight after relocating.
- Route params win in
rc. The merge order is query, then form body, then route params, so a form field called id can't replace the :id in the URL.
- A field sent twice is an array.
title=a&title=b gives rc.title as [ "a", "b" ], where ColdBox gives a list. _cleanTitle() checks isSimpleValue() before trimming for that reason.
- Injection is by name, from a struct. The
services struct passed to boxExpressMvc() has a todoService key and the handler has a property of that name, so it gets set once at startup. If you want real WireBox, pass injector: yourInjector and write property name="todoService" inject="TodoService"; as usual. Standalone WireBox 8.3 works with it.
And the one that matters most:
A handler is one object shared by every request, and requests run at the same time. Never store anything about the current request in the handler's variables scope. variables.todo = … in preHandler would be overwritten by the next request before your action read it. That is why the todo goes in prc.
This is true in ColdBox as well. Handlers are singletons there too.
Step 6: the layout
<!-- layouts/Main.bxm -->
<bx:output><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>#encodeForHTML( prc.title ?: "Todos" )#</title>
</head>
<body>
<h1><a href="#event.buildLink( "todos.index" )#">Todos</a></h1>
#view()#
</body>
</html>
</bx:output>
(The version in the repo has a block of CSS in the <head> as well.)
ColdBox similarity: layouts/Main is the default layout, and #view()# is where the rendered view goes. event.setLayout( "Other" ) and event.noLayout() change it for one request. The order is the ColdBox order: action, then view, then layout, so the action or the view can set prc.title for the layout.
Different from ColdBox: the files are .bxm, BoxLang's template format. <bx:output> is <cfoutput>, <bx:loop> is <cfloop>, <bx:if> is <cfif>. And #…# is only evaluated inside <bx:output>.
Step 7: the views
<!-- views/todos/index.bxm -->
<bx:output>
<form method="post" action="#event.buildLink( "todos.create" )#">
<input type="hidden" name="_csrf" value="#encodeForHTMLAttribute( event.getRequest().csrfToken() )#">
<input type="text" name="title" placeholder="What needs doing?" maxlength="200" autofocus>
<button>Add</button>
</form>
<bx:if ( rc.error ?: "" ) == "title">
<p class="error">A todo needs a title.</p>
</bx:if>
<nav>
<bx:loop list="all,active,done" item="name">
<a href="#event.buildLink( "todos.index", name == "all" ? {} : { filter: name } )#" class="#name == prc.filter ? "current" : ""#">#name# (#prc.counts[ name ]#)</a>
</bx:loop>
</nav>
<ul>
<bx:loop array="#prc.todos#" item="todo">
#view( "todos/item", { todo: todo } )#
</bx:loop>
</ul>
<bx:if prc.todos.isEmpty()>
<p>Nothing here.</p>
</bx:if>
<footer>
<span>#prc.counts.active# left</span>
<bx:if prc.counts.done GT 0>
<form method="post" action="#event.buildLink( "todos.clearCompleted" )#"><input type="hidden" name="_csrf" value="#encodeForHTMLAttribute( event.getRequest().csrfToken() )#"><button>Clear completed</button></form>
</bx:if>
</footer>
</bx:output>
<!-- views/todos/item.bxm -->
<bx:output>
<li class="#args.todo.done ? "done" : ""#">
<form method="post" action="#event.buildLink( "todos.toggle", { id: args.todo.id } )#">
<input type="hidden" name="_csrf" value="#encodeForHTMLAttribute( event.getRequest().csrfToken() )#">
<button title="Toggle">#args.todo.done ? "&##9745;" : "&##9744;"#</button>
</form>
<span class="title">#encodeForHTML( args.todo.title )#</span>
<a href="#event.buildLink( "todos.edit", { id: args.todo.id } )#">edit</a>
<form method="post" action="#event.buildLink( "todos.delete", { id: args.todo.id } )#">
<input type="hidden" name="_csrf" value="#encodeForHTMLAttribute( event.getRequest().csrfToken() )#">
<button title="Delete">×</button>
</form>
</li>
</bx:output>
<!-- views/todos/edit.bxm -->
<bx:output>
<form method="post" action="#event.buildLink( "todos.update", { id: prc.todo.id } )#">
<input type="hidden" name="_csrf" value="#encodeForHTMLAttribute( event.getRequest().csrfToken() )#">
<input type="text" name="title" value="#encodeForHTMLAttribute( prc.todo.title )#" maxlength="200" autofocus>
<button>Save</button>
<a href="#event.buildLink( "todos.index" )#">Cancel</a>
</form>
<bx:if ( rc.error ?: "" ) == "title">
<p class="error">A todo needs a title.</p>
</bx:if>
</bx:output>
ColdBox similarity:
- Views see
rc, prc and event as bare names.
#view( "todos/item", { todo: todo } )# renders another view inline, and that view reads what it was given as args.todo. That is ColdBox's view( view = "…", args = {} ).
event.buildLink( "todos.toggle", { id: 3 } ) turns a handler.action into a URL. It finds the route for that action and fills in :id, giving /todos/3/toggle. Anything that isn't a placeholder becomes the query string, which is how the filter links get ?filter=active. No URL in these views is written by hand, so the routes file can change without touching them.
Same as ColdBox, and worth repeating: output is not escaped for you. Every value that came from a user goes through encodeForHTML(), or encodeForHTMLAttribute() when it lands inside an attribute. Add a todo called <script>alert(1)</script> to see why.
Different from ColdBox:
- The CSRF token comes from the request, not a helper.
event.getRequest() is the BoxExpress req, and csrfToken() is what the CSRF middleware put on it. This is the escape hatch in use: the MVC layer has no CSRF feature and doesn't need one.
- The encoders come from
bx-esapi. Only encodeForHTML() is built into BoxLang. encodeForHTMLAttribute() and the rest of the family are in the bx-esapi module, which is why it was in the install command in step 1. Put it in every app.
Step 8: run it
boxlang server.bxs
Open http://localhost:3000. Add a todo, tick it, rename it, clear the completed ones. http://localhost:3000/api/todos is the same list as JSON.
Editing a .bxm file shows up on the next request. Handlers, the model and the routes file are loaded once, so they need a restart. While developing, start it this way and BoxExpress restarts the server whenever one of those files changes:
APP_ENV=development boxlang server.bxs
That is the reloadOnChange line in server.bxs. There is no ?fwreinit.
The example also has a Dockerfile that installs the three modules from ForgeBox on top of the ortussolutions/boxlang:cli image:
docker build -t todo . && docker run --rm -p 3000:3000 todo
What it compiles to
None of the above runs through a front controller at request time. When boxExpressMvc() returns, the route table holds the equivalent of this:
router.get( "/", ( req, res, next ) => /* run todos.index */ )
router.post( "/", ( req, res, next ) => /* run todos.create */ )
router.post( "/todos/:id(\d+)/toggle", ( req, res, next ) => /* run todos.toggle */ )
// …
Each of those closures already holds its handler instance and action name. Per request, the module builds rc, wraps req and res in an event, and calls your function. There is no scanning of folders and no lookup by name.
That also means you can leave whenever you want:
- A route can be a plain
( req, res ) function, like /healthcheck above.
- Inside an action,
event.getRequest() and event.getResponse() are the BoxExpress req and res. Cookies, sessions, res.sendFile(), server-sent events: anything BoxExpress does is one call away.
- Middleware goes in front the usual way:
app.use( "/admin", requireAdmin, mvc.router() ). Whatever it puts in res.locals arrives in your action as prc, because prc is res.locals.
What is not there
It is a 0.1.0, and a deliberately small one:
- No interceptors or
announce(). Use middleware.
- No ColdBox modules, no HMVC, no CBWIRE.
- No
aroundHandler, onMissingAction or this.allowedMethods.
- No flash scope, HTML helper or
_method override.
- No CacheBox or LogBox integration.
The todo app itself keeps its data and its sessions in memory, so a restart brings back the two starter todos and everyone's next form post gets a 403 until they reload the page. A real app would give the service a database and the session middleware a durable store.
The repo has a longer guide for ColdBox developers, Coming from ColdBox, with a table mapping each ColdBox concept to its equivalent here and to plain BoxExpress.
Links
It needs BoxLang Express 0.2.27 or later and BoxLang 1.15 or later; the test suite runs on 1.15 through 1.19. If you try it and something that should feel like ColdBox doesn't, open an issue.
No comments yet — be the first.