Skip to content

Commit

Permalink
Enables to toggle server side rendering when running the server. Conf…
Browse files Browse the repository at this point in the history
…iguration has a new key named `serverSideRendering` that can be toggled between `true` and `false`. Related to: kriasoft#642, kriasoft#634
  • Loading branch information
totty90 committed Sep 5, 2016
1 parent 302a69c commit a6062d4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 22 deletions.
1 change: 1 addition & 0 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

export const port = process.env.PORT || 3000;
export const host = process.env.WEBSITE_HOSTNAME || `localhost:${port}`;
export const serverSideRendering = true;

export const databaseUrl = process.env.DATABASE_URL || 'sqlite:database.sqlite';

Expand Down
44 changes: 22 additions & 22 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import models from './data/models';
import schema from './data/schema';
import routes from './routes';
import assets from './assets'; // eslint-disable-line import/no-unresolved
import { port, auth } from './config';
import { port, auth, serverSideRendering } from './config';

const app = express();

Expand Down Expand Up @@ -84,31 +84,31 @@ app.use('/graphql', expressGraphQL(req => ({
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
let css = new Set();
let statusCode = 200;
const data = { title: '', description: '', style: '', script: assets.main.js, children: '' };

await UniversalRouter.resolve(routes, {
path: req.path,
query: req.query,
context: {
insertCss: (...styles) => {
styles.forEach(style => css.add(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len
if (serverSideRendering) {
let css = new Set();
await UniversalRouter.resolve(routes, {
path: req.path,
query: req.query,
context: {
insertCss: (...styles) => {
styles.forEach(style => css.add(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len
},
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
render(component, status = 200) {
css = new Set();
statusCode = status;
data.children = ReactDOM.renderToString(component);
data.style = [...css].join('');
return true;
},
});

render(component, status = 200) {
css = new Set();
statusCode = status;
data.children = ReactDOM.renderToString(component);
data.style = [...css].join('');
return true;
},
});
}
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);

res.status(statusCode);
res.send(`<!doctype html>${html}`);
} catch (err) {
Expand Down

0 comments on commit a6062d4

Please sign in to comment.