Skip to content

Instantly share code, notes, and snippets.

@ovpv
Last active August 7, 2019 09:39
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 ovpv/6e69b50856d287cf79ffa6420e54da89 to your computer and use it in GitHub Desktop.
Save ovpv/6e69b50856d287cf79ffa6420e54da89 to your computer and use it in GitHub Desktop.
Routing in server.js
import express from "express";
import React from "react";
import { renderToString } from "react-dom/server";
import { StaticRouter as Router } from "react-router-dom";
import path from "path";
import App from "./client/app";
const app = express();
const port = 3000;
import Routes from "./routes";
const HTML = (req, context) => {
const body = renderToString(
<Router location={req.url} context={context}>
<App />
</Router>
);
return `<html>
<head>
<title>React Basic SSR</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body style="margin:0;">
<div id="app">
${body}
</div>
<script src="client.js"></script>
</body>
</html>`;
};
const context = {};
app.use(express.static("dist"));
app.get("*", (req, res) => {
return res.send(HTML({ url: "/404" }, context));
});
Routes.forEach(route => {
app.get(route.url, (req, res) => {
return res.send(HTML(req, context));
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment