node package manager
Easy collaboration. Discover, share, and reuse code in your team. Create a free org »

shared-context

Shared Data Context for Node and the Browser

NPM Version NPM Downloads Build Status js-happiness-style

This module provides a middleware which is easily used to share data between the front and back end. The data is properly escaped for insertion directly into the html of a page to protect you against script injection attacks. This is a common pattern used for applications that have heavy front-end javascript components like React or Angular apps.

If you are using an isomorphic router pattern, like the Express with Nighthawk, you can use this middleware on both sides and it will handle the data loading for you. Check out the example for more details on this pattern.

Usage

$ npm install --save shared-context
// index.js 
 
var app = require('express')();
var sharedContext = require('shared-context');
 
app.use(sharedContext({
    // Options and their defaults 
 
    // The global variable which should be set and loaded from 
    // browserVar: '__context', 
 
    // The variable which is set on `res.locals` 
    // localsVar: 'context', 
 
    // Set globals that are included in every request, 
    // even front-end page changes with a FE router like nighthawk 
    // globalsVar: '__$globals', 
    // globals: {} 
}));
 
app.get('/', function (req, res) {
    // Set some data on the context, 
    // in a real app this would come from 
    // some api or other data source 
    res.locals.context.title = 'Foo\'s Day at the Bar';
 
    // Render the template 
    res.render('index');
});
<html>
    <!-- other stuff in here -->
    <script>
        __context = <%- JSON.stringify(context) %>
    </script> 
    <script src="/browser.js"></script> 
</html>
// browser.js 
 
var app = require('nighthawk')();
var sharedContext = require('shared-context');
 
app.use(sharedContext());
 
app.get('/', function (req, res) {
    // Do browser type stuff, like bind events 
    // or render a react applicaion 
    console.log(res.locals.context.title); // 'Foo\'s Day at the Bar' 
});