Skip to content

Instantly share code, notes, and snippets.

@jdltechworks
Last active May 9, 2019 05:28
Show Gist options
  • Save jdltechworks/63d386f35ab5127678e40b8cc3f05e1c to your computer and use it in GitHub Desktop.
Save jdltechworks/63d386f35ab5127678e40b8cc3f05e1c to your computer and use it in GitHub Desktop.
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: `!!raw-loader!${path.join(__dirname, 'client/index.ejs')}`,
filename: path.resolve(__dirname, './server/templates/index.ejs'),
inject: 'body',
});
import React from 'react';
import serialize from 'serialize-javascript';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { match, createMemoryHistory, RouterContext } from 'react-router';
import routes from 'routes/routes';
import createStore from 'store/server';
import { snakeToCamelCase } from 'json-style-converter/es5';
const ServerProvider = (req, res) => {
const initialState = { user: (req.user && snakeToCamelCase(req.user.hidePassword())) || {} };
const store = createStore(initialState);
const memoryHistory = createMemoryHistory(req.url);
const history = syncHistoryWithStore(memoryHistory, store);
const { meta } = req;
match({ history, routes, location: req.url },
(error, redirectLocation, renderProps) => {
if (error) return res.status(500).send(error.message);
if (redirectLocation) {
return res.redirect(
302,
redirectLocation.pathname + redirectLocation.search,
);
}
const has404 = renderProps.routes.find(r => r.status === 404) !== undefined;
if (has404) {
try {
res.status(404);
} catch (error) {
console.log('ServerProvider error', error);
}
}
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>,
);
return res.render('index', {
meta,
content,
preloadedState: serialize(store.getState()),
});
});
};
export default ServerProvider;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<% if (meta) { %>
<meta title="<%= meta.title %> | Flyspaces">
<meta description="<%= meta.description %>">
<% } %>
<% if (meta) { %>
<title><%= meta.title %> | Ninja spaces</title>
<% } %>
<link rel="shortcut icon" type="image/png" href="/favicon-new.ico" />
<link rel="shortcut icon" type="image/x-icon" href="/favicon-new.ico" />
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PZCC6M" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div id="app"><%-content%></div>
<script>
window.INITIAL_STATE = <%-preloadedState%>;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment