Skip to content

Instantly share code, notes, and snippets.

@danecando
Last active July 26, 2017 01:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danecando/9fdb52ca63d9bd7416ec to your computer and use it in GitHub Desktop.
Save danecando/9fdb52ca63d9bd7416ec to your computer and use it in GitHub Desktop.
Fluxible server side rendering with Hapi
'use strict';
require('babel/register');
var Hapi = require('hapi');
var db = require('./db');
var serialize = require('serialize-javascript');
var navigateAction = require('flux-router-component').navigateAction;
var debug = require('debug')('Example');
var React = require('react');
var app = require('./flux/app');
var HtmlComponent = React.createFactory(require('./flux/components/Html.react'));
var server = new Hapi.Server();
/**
* Create server connection
*/
server.connection({
host: 'localhost',
port: 7000
});
/**
* Serve assets
*/
server.route([
{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: 'public'
}
}
}
]);
// this is a hook into hapi's request lifecycle see: http://hapijs.com/api#request-lifecycle
// this is the hapi equivilent to the express middleware
server.ext('onPostHandler', function(request, reply) {
// as you can see the code in here is quite simmilar to the express example
var context = app.createContext();
debug('Executing navigate action');
// check the requested route
context.executeAction(navigateAction, {
url: request.url.path
}, function(err) {
if (err) {
if (err.status && err.status === 404) {
return reply.continue();
}
return;
}
debug('Exposing context state');
var exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
debug('Rendering Application component into html');
var AppComponent = app.getAppComponent();
// render our component to html
var html = React.renderToStaticMarkup(HtmlComponent({
state: exposed, // @todo attach state to response object instead. see: express-state
markup: React.renderToString(AppComponent({context: context.getComponentContext()})),
context: context.getComponentContext()
}));
debug('Sending markup');
// and send it off as the response
reply(html);
});
});
server.start(function(err) {
if (!err) {
console.log('Server started at: ' + server.info.uri);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment