Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

bem-node Build Status

Single-page web application with node.js, BEM


Use bem-node with our project-stub

How it works

The main principle of bem-node is presenting page layout as bemjson (russian ref) object. Block templates apply on bemjson tree to produce complete layout with data. Then bemjson is serialising to html.


File extensions


Browser code


Common (client/server) code


Private (server) code


Builded node.js application (server)


Application declaration

// application declaration example
exports.blocks = [

    // bem-node part
    {block: 'i-console'}, //colorful console log
    {block: 'i-enb'}, //output static files

    // pages
    {block: 'hello-world'}


Block dependencies

//block dependencies example
    shouldDeps: [
        {block: 'depended-block'}
    mustdDeps: [
        {block: 'must-dependeded-block'} //should be included before target block


Block constructor. It creates i-bem (russian guide, english guide) blocks with static and dom declarations, and bh (russian ref) templates.


  • blockName {String}
  • return {Object} bem block

Returns link on BEM block static methods and properties.

BN.addDecl(blockName , [type], [options])

  • blockName {String}
  • [type] {String} - must be "page" or "ajax", if defined
  • [options] {Object}
  • [options.route] {String|RegExp} route for blocks with type="page"
  • [options.apiHost] {String} api host for blocks with type="ajax"
  • return {BN.Generator} bem block generator

Creates block generator.


  • returns {BN.Generator}

Inherits block declaration from base block.


  • decl {Object} static methods and properties
  • return {BN.Generator}

Adds static methods and properties (i-bem).

    someProp: 'a',
    someMethod: function(){
        return this.someProp + 'b';

BN('example').someMethod(); //returns 'ab'

    someMethod: function(){
        return this.__base() + 'c';

BN('example').someMethod(); //returns 'abc'

this – inherits i-bem

this.__instances – array of block dom instances (only for client side code)

this.__lastInstance – last created block instances (only for client side code)


  • decl {Object} dom instances methods and properties
  • return {BN.Generator}

Adds methods and properties for block dom instance (i-bem.dom)


  • decl {Object|Function} define block bh template
  • return {BN.Generator}


  • decl {Object} define block element bh template
  • return {BN.Generator}

Creates bh templates (see bh) for block, elements and it's modifications.

 * Example of block with element
BN.addDecl('example').blockTemplate(function (ctx) {
    //block template
        {elem: 'item', url: 'item-1', text: 'item 1'},
        {elem: 'item', url: 'item-1', text: 'item 2'}
    'item': function (ctx) {
        //element template
        var json = ctx.json();
            block: 'b-link',
            url: json.url,
            content: json.text

ctx is instances of bh.Ctx


  • decl {Function} define block data template
  • return {BN.Generator}

decl can return promise (see Vow.promise). If promise is fulfilled, other block templates will be applied. If promise is rejected, block will be removed.

    return BN('some-ajax-block').get().then(function(data){
        ctx.param('data', data) //set data to block property
        return Vow.fulfill();
        ctx.content(ctx.json().data.text); //ouput data

ctx is instance of bh.Ctx


Creates i-bem block from generator and adds bh matchers. All blocks will be created automatically on next event loop. Use this methods only to force block creation.

Page blocks

Page block are controllers for pages.

 * Hello world page
BN.addDecl('hello-world', 'page', {
    route: /^\/$/
    init: function () {
        return this.out('hello world');

All pages are extended from i-page block.

BN.addDecl('usual-page', 'page', {
    route: /^\/$/ //page route
    init: function (matchers) {
        return this.out(/*bemjson*/);
    update: function(matchers, prevPath, newPath) {
       return Vow.fulfill();
    destruct: function() {
       return Vow.fulfill();

route is {RegExp} or {String} which can be matched to request url.

init is called when page route match to request url. Init should return fulfilled promise. Otherwise page returns error.

update is called when page should be updated on client (new url matched with the same route). By default update calls init

destruct is called on client side before current page is going to be replaced with other page.

Page blocks are extended from i-page block.

Ajax blocks

Ajax blocks are kind of models (or data blocks). They can provide data to view blocks with common interface between client and server.

On server: get → _request (server implementation) → REST API

On client: get → _request (client implementation) → ajax request → _request (server implementation) → REST API

// example-ajax-block.common.js
BN.addDecl('example-ajax-block', 'ajax', {
    apiHost: '' //json api provider
//get data from
BN('example-ajax-block').get('some/resource', {
    params: {
        count: 10

Ajax blocks are inheriting from 'i-api-request' block. You can extend block methods to provide additional input params and output data processing:

 * Fetching data from node.js doc api
BN.addDecl('node-doc-api', 'ajax', {
    apiHost: ''
     * Add .json to resources
     * @overide
    get: function (resource) {
        resource = resource + '.json';
        return this.__base(resource);

By default ajax blocks have only GET method. To provide POST PUTandDELETE` you should declare them:

// ajax block supporting post
BN.addDecl('example-ajax-block', 'ajax', {
    apiHost: '' //json api provider
    post: function (resource, options) {
        return this._request('post', resource, options)

You are able to extend ajax block to fetch data from any source (like database).

Existing blocks

Bem-node includes some visual blocks from bem-bl library

Overriding existing blocks

Power of BEM is ability to override almost any method, template or style of block:

//change content of b-page by adding block b-head
BN.addDecl('b-page').blockTemplate(function (ctx) {
        {block: 'b-head'},
    ], true);


This is a base block for page blocks. But some of the static methods can be called from other blocks (issue).


  • title {String}
  • return {Object} this

Setting page <title/> on client and on server


  • text {String}
  • return {Object} this

Setting page description meta tag on client and on server

BN('i-page').setMeta(name, content)

  • name {String} name attribute of <meta/>
  • content {String} content attribute of <meta/>
  • return {Object} this

Setting page <meta/> tags


  • bemjson {Object|String}
  • return {Object} this

Adds to page <head/> any content


  • matchers {Array} result of appling route regexp on url
  • return {Vow.promise}

This method is called when page route match to url. Redefine this method to output your page layout. See example in page blocks and i-page.out method. By default page outputs empty string.

.update(matchers, prevPath, newPath)

  • matchers {Array} result of appling route regexp on url
  • prevPath {String} url path before update
  • newPath {String} new url path
  • return {Vow.promise}

This method is called when page should be updated on client (new url matched with the same route). By default it calls `this.init(). You can setup selective block updates by redefining this method.

 * Node docs page
BN.addDecl('node-doc', 'page', {
    route: /^\/node-doc\/?(.+)?$/
    //calls on page render
    init: function (matches) {
        var section = this._getSectionName(matches);
        this.setTitle(section + ' – node.js api'); //set page title
        //output page layout
        return this.out({
            block: 'node-doc',
            content: [
                {elem: 'toc', content: {block: 'node-doc-toc'}},
                {elem: 'section', content: {block: 'node-doc-section', section: section}}

    _getSectionName: function (matches) {
        return matches[1] || 'documentation'; //set section from url

    //update page on client
    update: function (matches) {
        var section = this._getSectionName(matches);
        return BN('node-doc-section').updateSection(section);


  • return {Vow.promise}

Is called when user leaves page on client and page should be destructed. Extend this method for custom calls on destruct.


  • bemjson {Object|String} page content
  • return {Vow.promise}

On server:

  • wrap bemjson with static layout (header, footer, etc); you can override static layout by redefining getPageJson(); page content should be placed in i-content block;
  • process bemjson
  • serialise bemjson to html
  • send http response 200 OK with resulting html

On client:

  • process bemjson
  • serialise bemjson to html
  • update i-content block content with resulting html
  • init blocks inside i-content

Use it to output page layout from page blocks. Do not call BN('i-page').out(bemjson), use only this.out(bemjson)

 * Node docs page
BN.addDecl('node-doc', 'page', {
    route: /^\/node-doc\/?(.+)?$/
    init: function () {
        return this.out({ //this works on client and server
            block: 'node-doc',
            content: [
                {elem: 'toc', content: {block: 'node-doc-toc'}},
                {elem: 'section', content: {block: 'node-doc-section'}}


This block is a container for pages content. Content inside i-content can be automatically updated on client.

Block has api to manipulate content inside pages.

BN('i-content').html(bemjson, [isSync=false])

  • bemjson {Object|String}
  • [isSync=false] {Boolean}
  • return {Vow.promise|String} rendered html

Applies all supported templates (bh, bem.json, bemhtml) to bemjson tree and then serialises it to html.

By setting isSync = true you will get error when rendering blocks with defined dataTemplate.

BN('i-content').update | replace | append | before(container, bemjson)

  • container {Object} jQuery object
  • bemjson {Object}
  • return {Vow.promise}

Update dom with new content.

    //.. adding some content
    /.. adding some data to params
    updateBlock: function(param) {
        return BN('i-content').update(this.__lastInstance.domElem.parent(), {
            block: this._name,
            param: param


Manages error pages (404, 50x), http redirect and responses.

BN('i-response').send(status, body, [contentType='text/plain'])

  • status {Number} http status
  • body {String}
  • [contentType='text/plain'] {String}

Sends http response.


Responses with json.


Redirects to path with 302 status.


Responses with 404 status.


  • err {Error|HttpError} http status

Responses with error (503 or status, defined in HttpError) and log error.

//block sends error when data fetching fails
    var resource = ctx.json().resourceParam; //geting block param
    return BN('ajax-block').get(resource).then(function(dataJson){ //get data from ajax block
        ctx.param('data', dataJson); //setup data in block param
        Vow.fulfill(); //continue render
    }).fail(function(err){ // if data fails
        BN('i-response').error(err); //send error to user
        return Vow.reject(err); // stop render


Create user errors

new BN('i-errors').CommonError(message)

  • message {String}

Constructor for user errors

new BN('i-errors').HttpError(status)

  • status {Number} http status

Https error.

var Errors = BN('i-errors');
var ApiError = function (status, debugInfo) {, status); = 'ApiError';
  this.debugInfo = debugInfo;
ApiError.prototype = new HttpError();
ApiError.prototype.constructor = ApiError;

//to properly serialize
Errors.ApiError = ApiError;
ApiError.prototype.serialize = function () {
    var errorObj =;
    errorObj.args = [this.status, this.debugInfo];
    return errorObj;

var err = new ApiError(404, 'fail');
err instanceof Error; //true
err.message; //Not Found
err.debugInfo; //fail


  • err {Error}

Returns instance of object with error properties. Can be serialised to JSON


  • obj {*}

Returns error.

var Errors = BEM.blocks['i-errors'];
  error: Errors.serialize(new Errors.HttpError(404))
var Errors = BEM.blocks['i-errors'];
var data = JSON.parse(xhr.responseText);
var err = Errors.createError(data.error);


Manages page blocks and transitions between urls.

BN('i-router').setPath | replacePath(path, [allowFallback=false])

  • path {String}
  • [allowFallback=false] {Boolean} if history.pushState is not supported, reload page to render on server

Changes url path.

On server: redirects with 302.

On client: destructs current page and inits new page. setPath uses history.pushState; replacePath uses history.replaceState.


Returns url path


Returns full uri (i.e. protocol, domain, path, query)

BN('i-router').setParams | replaceParams(params, [allowFallback=false], [extend=false])

  • params {Object} key-value map of url params
  • [allowFallback = false] {Boolean} if history.pushState is not supported, reload page to render on server
  • [extend = false] {Boolean} extend current url params with new one

Changes url params.

On server: redirects with 302.

On client: setParams uses history.pushState; replaceParams uses history.replaceState.


Returns url host.

BN('i-router').escapeHTML | unescapeHTML (html)

DEPRECATED — use BN('i-content').escapeHTML | unescapeHTML instead

Escapes user content to prevent XSS.


GET or POST params.


Node http.IncomingMessage


Node http.ServerResponse


Request cookies. See node-cookie api;


Getting regexp matchers from current router

Event 'update'

Use it to update static page content on client:

//example of static header that updates when page changing
    init: function () { //fires when block inits on client
        BN('i-router').on('update', this._onPageUpdate); //listen to page updates
    _onPageUpdate: function () {
        this.elem('search-input').val( //change value of search input element
            BN.escapeHTML( //escape to prevent XSS
                BN('i-router').getParams().q //get param from url


Base block for ajax blocks.

.get(resource, [options])

Calls this._request('get', resource, options);

._request(method, resource, [options])

  • method {string} http method
  • resource {string} REST api resource
  • [options] {Object}
  • [options.params] {Object} REST api request params
  • [options.body] {Object} REST api request body

On server: makes request to rest api host, defined by this._apiHost.

On client: makes remote call (through xhr) of server implementation.

Event 'beforerequest' 'afterrequest'

Triggered on client before and after xhr request.

BN('i-api-request').on('beforerequest', function () {
    //show ajax loader
BN('i-api-request').on('afterrequest', function () {
    //hide ajax loader

Event 'error'

Triggered on client on xhr error.


run tests

git clone
cd bem-node
npm test

quick tests

./ -c #client tests only
./ -s #server tests only
./ -s -n simple #run server tests only for 'simple' set
./ -s -n simple -g i-router #grep i-router tests
./ -b #rebuild tests
./ -b -s -c #rebuild, server, client

create tests

You should use .common.test.js for tests common for client and server, .priv.tests.js for server tests only, and .tests.js for client tests only.

Typical test looks like this

describe('whatever', function () {
    it ('testing someting', function (done) {
        return expect(env('/some-url?param-name=param-value', function () {
            return <promise or not>
        })).eventually.equal(<some value>)
describe('i-api-request', function () {
    it('get with full path', function () {
        return expect(env(function () {
            return BEM.blocks['i-api-request'].get('')

You should use global env function to create page context