Last active
April 24, 2017 19:33
-
-
Save AlexMold/f3d3581926aae61ccb65d07b3fcb30be to your computer and use it in GitHub Desktop.
react-ssr-server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// React modules | |
import { RouterContext, match } from 'react-router' | |
import { renderToString, renderToStaticMarkup } from 'react-dom/server' | |
import React from 'react' | |
import NotFound from './frontend/containers/NotFound' | |
import routes from './routes' | |
import Html from './frontend/containers/Html' | |
app.use(async (ctx) => { | |
await match({ routes, location: ctx.request.url }, async (error, redirectLocation, renderProps) => { | |
if (redirectLocation) { | |
ctx.redirect(redirectLocation.pathname + redirectLocation.search) | |
} else if (error || !renderProps) { | |
ctx.throw(500, error.message) | |
} | |
// set proper HTTP code for if matched route wasn't found | |
if (renderProps.components.indexOf(NotFound) != -1) { | |
ctx.status = 404; | |
} | |
/** | |
* must take Store(redux) object | |
* | |
*/ | |
const render = () => { | |
const content = renderToString(<RouterContext {...renderProps} />) | |
const assets = global.assets | |
const markup = <Html content={content} /> | |
const doctype = '<!doctype html>\n' | |
const html = renderToStaticMarkup(markup) | |
ctx.response.body = doctype + html; | |
} | |
await render(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment