express 0.1.6

  • Installing
  • Versions
  • 18

Dart Express

A simple, thin expressjs inspired layer around Dart's primitive HttpServer APIs. Also included is a single static file server module.

This library will eventually expand to help with other common usage patterns and features as and when needed.

Installing via Pub

Add this to your package's pubspec.yaml file:

  express: 0.1.6

Example Usages

Basic Jade and Express app

basic jade and express app screenshot

import "package:jaded/jaded.dart";
import "package:express/express.dart";
import "dart:io";

import "views/jade.views.dart" as views;
import "public/jade.views.dart" as pages;

  int counter = 0;
  var app = new Express()
    ..use(new JadeViewEngine(views.JADE_TEMPLATES, pages:pages.JADE_TEMPLATES))
    ..use(new StaticFileHandler("public"))
    ..get('/', (ctx){
      ctx.render('index', {'title': 'Home'});
    ..get('/error', (ctx){
      throw new ArgumentError("custom error in handler");
    ..get('/counter', (ctx){
      ctx.sendJson({'counter': counter++});

  app.listen("", 8000);

Static files used by this app

  • /public
    • /stylesheets
      • style.css
    • layout.jade - layout for .jade pages called directly (i.e. no explicit route required)
    • layout-plain.jade - an alternative layout used by page.jade
    • static.jade - a static home page
    • page.jade - another page with layout-plain and inline :markdown content
    • - a markdown partial
    • jade.yaml - tell express to watch and pre-compile .jade views in this directory
    • jade.views.dart - the auto-generated pre-compiled .jade views for this directory
  • /views
    • layout.jade
    • index.jade
    • - a markdown partial
    • jade.yaml - tell express to watch and pre-compile .jade views in this directory
    • jade.views.dart - the auto-generated pre-compiled .jade views for this directory

Pre-compile .jade views on save

This example uses the Dart Editor build.dart Build System to compile all .jade views in any directory that contains an empty jade.yaml file.

To trigger this in your project add this to your projects /build.dart file:

import "package:express/express_build.dart" as express;


Backbone Todo's JSON Server

This is an example of an Redis-powered REST backend Backbones.js demo TODO application:

var client = new RedisClient();

var app = new Express();
  .use(new StaticFileHandler())

  .get("/todos", (HttpContext ctx){
    redis.keys("todo:*").then((keys) =>
  .get("/todos/:id", (HttpContext ctx){
    var id = ctx.params["id"];
    redis.get("todo:$id").then((todo) =>
      todo != null ?
        ctx.sendJson(todo) :
        ctx.notFound("todo $id does not exist")
  .post("/todos", (HttpContext ctx){
        var todo = $(x).defaults({"content":null,"done":false,"order":0});
        todo["id"] = newId;
        redis.set("todo:$newId", todo);
  .put("/todos/:id", (HttpContext ctx){
    var id = ctx.params["id"];
      redis.set("todo:$id", todo);
  .delete("/todos/:id", (HttpContext ctx){
  app.listen("", 8000);


Register encapsulated Modules like StaticFileHandler

abstract class Module {
  void register(Express server);

The signature your Request Handlers should implement:

typedef void RequestHandler (HttpContext ctx);

The core Express API where all your Apps modules and request handlers are registered on. Then when the server has started, the request handler of the first matching route found will be executed.

abstract class Express {
  factory Express() = _Express;
  //Sets a config setting
  void config(String name, String value);

  //Gets a config setting
  String getConfig(String name);

  //Register a module to be used with this app
  Express use(Module module);

  //Register a request handler that will be called for a matching GET request
  Express get(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching POST request
  Express post(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching PUT request
  Express put(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching DELETE request
  Express delete(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching PATCH request
  Express patch(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching HEAD request
  Express head(String atRoute, RequestHandler handler);

  //Register a request handler that will be called for a matching OPTIONS request
  Express options(String atRoute, RequestHandler handler);

  //Register a request handler that handles ANY verb
  Express any(String atRoute, RequestHandler handler);
  //Register a custom request handler. Execute requestHandler, if matcher is true.
  //If priority < 0, custom handler will be executed before route handlers, otherwise after. 
  void addRequestHandler(bool matcher(HttpRequest req), void requestHandler(HttpContext ctx), {int priority:0});

  //Alias for registering a request handler matching ANY verb
  void operator []=(String atRoute, RequestHandler handler);

  //Can any of the registered routes handle this HttpRequest
  bool handlesRequest(HttpRequest req);

  // Return true if this HttpRequest is a match for this verb and route
  bool isMatch(String verb, String route, HttpRequest req);

  // When all routes and modules are registered - Start the HttpServer on host:port
  Future<HttpServer> listen([String host, int port]);
  //render a view
  void render(HttpContext ctx, String viewName, [dynamic viewModel]);
  /// Permanently stops this [HttpServer] from listening for new connections.
  /// This closes this [Stream] of [HttpRequest]s with a done event.
  void close();

A high-level object encapsulating both HttpRequest and HttpResponse objects providing useful overloads for common operations and usage patterns.

abstract class HttpContext implements HttpRequest {
  String routePath;
  HttpRequest  req;
  HttpResponse res;
  Map<String,String> get params;

  //Read APIs
  String get contentType;
  Future<List<int>> readAsBytes();
  Future<String> readAsText([Encoding encoding]);
  Future<Object> readAsJson({Encoding encoding});
  Future<Object> readAsObject([Encoding encoding]);

  //Write APIs
  String get responseContentType;
  void set responseContentType(String value);
  HttpContext head([int httpStatus, String statusReason, String contentType, Map<String,String> headers]);

  HttpContext write(Object value, {String contentType});
  HttpContext writeText(String text);
  HttpContext writeBytes(List<int> bytes);

  //Overloads for sending different content responses 
  void send({Object value, String contentType, int httpStatus, String statusReason});
  void sendJson(Object value, {int httpStatus, String statusReason});
  void sendHtml(Object value, [int httpStatus, String statusReason]);
  void sendText(Object value, {String contentType, int httpStatus, String statusReason});
  void sendBytes(List<int> bytes, {String contentType, int httpStatus, String statusReason});

  //Custom Status responses
  void notFound([String statusReason, Object value, String contentType]);

  //Format response with the default renderer
  void render(String, [dynamic viewModel]);

  //Close and mark this request as handled 
  void end();
  //If the request has been handled
  bool get closed;



Register the jaded view engine to render HTML .jade views. Supports both controller view pages and static page .jade templates.

app.use(new JadeViewEngine(views.JADE_TEMPLATES, pages:pages.JADE_TEMPLATES))


app.get('/', (HttpContext ctx){
  ctx.render('index', {'title': 'Home'});

Renders the /views/index.jade view with the {'title': 'Home'} view model.

A request without a matching route, e.g:

GET /page

Will execute the /public/page.jade template, passing these HTTP request vars as the viewModel:

Map viewModel = {
  'method': req.method,
  'uri': req.uri,
  'headers': req.headers,
  'request': req,
  'response': req.response,


Serve static files for requests that don't match any defined routes:

app.use(new StaticFileHandler('public'));

Serves static files from the /public folder.

Other APIs

// Register different Formatters
abstract class Formatter implements Module {
  String get contentType;
  String get format => contentType.split("/").last;
  String render(HttpContext ctx, dynamic viewModel, [String viewName]);

// The loglevel for express
int logLevel = LogLevel.Info;

// Inject your own logger, sensitive on logtypes (error, warning...)
typedef Logger(Object obj, {int logtype});
Logger logger = (Object obj, {int logtype}) => print(obj);


Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  express: ^0.1.6

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:express/express.dart';
Version Uploaded Documentation Archive
0.1.6 May 11, 2014 Go to the documentation of express 0.1.6 Download express 0.1.6 archive
0.1.5 May 10, 2014 Go to the documentation of express 0.1.5 Download express 0.1.5 archive
0.1.3 Sep 3, 2013 Go to the documentation of express 0.1.3 Download express 0.1.3 archive
0.1.2 Jul 7, 2013 Go to the documentation of express 0.1.2 Download express 0.1.2 archive
0.1.1 Jul 5, 2013 Go to the documentation of express 0.1.1 Download express 0.1.1 archive
0.1.0 Jul 1, 2013 Go to the documentation of express 0.1.0 Download express 0.1.0 archive
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Fix dependencies in pubspec.yaml.

Running pub upgrade failed with the following output:

ERR: The current Dart SDK version is 2.0.0.
 Because express depends on jaded >=0.1.1 which requires SDK version <2.0.0, version solving failed.

Health suggestions

Format lib/_express.dart.

Run dartfmt to format lib/_express.dart.

Format lib/_http_context.dart.

Run dartfmt to format lib/_http_context.dart.

Format lib/content_types.dart.

Run dartfmt to format lib/content_types.dart.

Fix additional 5 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/express.dart (Run dartfmt to format lib/express.dart.)
  • lib/express_build.dart (Run dartfmt to format lib/express_build.dart.)
  • lib/modules/jade_view_engine.dart (Run dartfmt to format lib/modules/jade_view_engine.dart.)
  • lib/modules/static_file_handler.dart (Run dartfmt to format lib/modules/static_file_handler.dart.)
  • lib/utils.dart (Run dartfmt to format lib/utils.dart.)

Maintenance issues and suggestions

Fix platform conflicts. (-20 points)

Error(s) prevent platform classification:

Fix dependencies in pubspec.yaml.

Package is too old. (-100 points)

The package was released more than two years ago.

Maintain (-20 points)

Changelog entries help clients to follow the progress in your code.

Add SDK constraint in pubspec.yaml. (-5 points)

For information about setting SDK constraint, please see

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use express.dart.