Skip to content

Instantly share code, notes, and snippets.

@alexfedoseev alexfedoseev/server.app.jsx Secret
Last active Aug 29, 2015

Embed
What would you like to do?
Server rendering: iteration 1
/* app/bundles/app/initters/server.jsx */
// Here we collect bundle specific stuff
// to pass it to shared initter with bundle `params`
import initter from 'app/libs/initters/server';
import getAsset from 'app/libs/getAsset';
import config from 'config/server.app';
import routes from '../routes/routes';
import Head from '../layouts/Head';
export default (req, res, next) => {
const { bundle } = config;
const params = {
// Name of the bundle
bundle,
// Routes
routes,
// <head> template
Head,
// Variables for Jade template
// Here we store paths to compiled assets to inject them in html
// Explore `getAsset` helper in `app/libs` folder
locals: {
jsAsset : getAsset(bundle, 'js'),
cssAsset : getAsset(bundle, 'css'),
vendorAsset: getAsset('vendor', 'js')
}
};
// Initializing app
initter(req, res, next, params);
}
/* app/libs/initters/server.jsx */
// This initter is shared between all bundles
import React from 'react';
import Router from 'react-router';
import Location from 'react-router/lib/Location';
import serialize from 'serialize-javascript';
import jade from 'jade';
export default (req, res, next, params) => {
// Storing params in variables
const { routes, bundle, locals, Head } = params;
// Creating location object for the server router
const location = new Location(req.path, req.query);
// Running the router
Router.run(routes, location, (error, initialState, transition) => {
// If something went wrong, responding with 500
if (error) return res.status(500).send(error);
try {
// Rendering <head> tag
// Using `renderToStaticMarkup` here,
// because we don't need React ids on these nodes
locals.head = React.renderToStaticMarkup(
<Head cssAsset={locals.cssAsset} />
);
// Rendering app
locals.body = React.renderToString(
<Router location={location} {...initialState} />
);
// Storing webpack chunks in variable
// to expose it as global var in html for production bundles
// It's related to long-term caching of assets (details below)
const chunks = __DEV__ ? {} : require('public/assets/chunk-manifest.json');
locals.chunks = serialize(chunks);
// Defining path to jade layout
const layout = `${process.cwd()}/app/bundles/${bundle}/layouts/Layout.jade`;
// Compiling initial html
const html = jade.compileFile(layout, { pretty: false })(locals);
// 😽💨
res.send(html);
} catch (err) {
// If something went wrong, responding with 500
res.status(500).send(err.stack);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.