Skip to content

Instantly share code, notes, and snippets.

@hiroppy
Created July 31, 2018 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroppy/1c89d73a12073bad0c187aaab4ca92c2 to your computer and use it in GitHub Desktop.
Save hiroppy/1c89d73a12073bad0c187aaab4ca92c2 to your computer and use it in GitHub Desktop.
import { Request, Response } from 'express';
import * as React from 'react';
import { Provider } from 'react-redux';
import { renderToNodeStream, renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { ServerStyleSheet } from 'styled-components';
import { HTML } from '../HTML';
import { Router } from '../../client/Router';
import { configureStore } from '../../client/store/configureStore';
import { rootSaga } from '../../client/sagas';
export function get(req: Request, res: Response) {
const store = configureStore();
const context = {};
const comp = (
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<Router />
</StaticRouter>
</Provider>
);
store
.runSaga(rootSaga)
.done.then(() => {
const preloadedState = store.getState();
const sheet = new ServerStyleSheet();
const jsx = <HTML initialData={JSON.stringify(preloadedState)}>{comp}</HTML>;
const jsxWithStyles = sheet.collectStyles(jsx);
const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsxWithStyles));
stream.pipe(
res,
{ end: false }
);
stream.on('end', () => res.send());
})
.catch((e: Error) => {
res.status(500).send(e.message);
});
// kick redux-saga
renderToStaticMarkup(comp);
// close redux-saga(because using `fork`)
store.close();
}
@hiroppy
Copy link
Author

hiroppy commented Jul 31, 2018

react-helmetがsteam未対応(ref: nfl/react-helmet#296)
styled-componetsがstyleタグを入れる場合、headに入れるのが難しい。。
サンプルですらbodyに入れている。 https://www.styled-components.com/docs/advanced#server-side-rendering

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment