Skip to content

Instantly share code, notes, and snippets.

@macrozone
Created October 14, 2018 17:09
Show Gist options
  • Save macrozone/637f66dbac7bf752b0814cdc0699b677 to your computer and use it in GitHub Desktop.
Save macrozone/637f66dbac7bf752b0814cdc0699b677 to your computer and use it in GitHub Desktop.
flow router ssr example with radium, helmet and fastrender
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import { FastRender } from 'meteor/staringatlights:fast-render';
import { InjectData } from 'meteor/staringatlights:inject-data';
import { Random } from 'meteor/random';
import { renderToString } from 'react-dom/server';
import React from 'react';
import Radium from 'radium';
import { Helmet } from 'react-helmet';
import Loadable from 'react-loadable';
import app from '/imports/modules/app';
InjectData.disableInjection = true;
const RadiumWrapper = Radium(
class extends React.Component {
/* eslint react/destructuring-assignment: 0 */
render() {
return this.props.children;
}
}
);
app.init();
Loadable.preloadAll().then(() => {
FastRender.onPageLoad(async sink => {
const randomSeed = Random.id();
const result = FlowRouter.matchPath(
sink.request.url.path,
sink.request.query
);
if (result) {
const { route, params } = result;
route.render = (Component, props) => {
console.log(`render ${sink.request.url.path}`);
console.time('rendertime');
const modules = [];
const modulesResolved = [];
const appString = renderToString(
<Loadable.Capture
report={moduleName => {
modules.push(moduleName);
}}
reportResolved={resolvedModuleName => {
modulesResolved.push(resolvedModuleName);
}}
>
<RadiumWrapper
radiumConfig={{ userAgent: sink.request.headers['user-agent'] }}
>
<Component {...props} randomSeed={randomSeed} />
</RadiumWrapper>
</Loadable.Capture>
);
console.timeEnd('rendertime');
const helmet = Helmet.renderStatic();
sink.appendToHead(helmet.title.toString());
sink.appendToHead(helmet.meta.toString());
sink.appendToBody(
`<script> var __randomSeed = "${randomSeed}";</script>`
);
sink.renderIntoElementById('react-root', appString);
sink.appendToBody(
`<script> var __preloadables__ = ${JSON.stringify(
modulesResolved
)};</script>`
);
// see https://github.com/abecks/meteor-fast-render/issues/23
FastRender._mergeFrData(
sink.request,
FastRender.frContext.get().getData()
);
const payload = `<script type="text/inject-data">${InjectData.encode(
sink.request.headers._injectPayload
)}</script>`;
sink.appendToBody(payload);
};
const { query } = sink.request;
const data = route.data ? route.data(params, query) : null;
route.action(params, query, data, { sink });
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment