Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

shared-context

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

shared-context

Share data with the browser with automatic escaping

latest
Source
npmnpm
Version
1.3.1
Version published
Weekly downloads
9
125%
Maintainers
1
Weekly downloads
 
Created
Source

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'
});

Keywords

data

FAQs

Package last updated on 14 Jul 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts