aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2022-10-28 00:14:01 +0300
committerGravatar Vitaly Takmazov2023-01-13 10:37:58 +0300
commit40d411e516efee5531404725b45ab89d97172ce8 (patch)
treed675e93fc52ef50a40343219e1b992867964d3bf /vnext/server/middleware
parent2146a98bd98b7e275a0ee7bc7a243981b597f34c (diff)
Initial SSR
Diffstat (limited to 'vnext/server/middleware')
-rw-r--r--vnext/server/middleware/renderer.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/vnext/server/middleware/renderer.js b/vnext/server/middleware/renderer.js
new file mode 100644
index 00000000..8edb5f57
--- /dev/null
+++ b/vnext/server/middleware/renderer.js
@@ -0,0 +1,48 @@
+import ReactDOMServer from 'react-dom/server';
+import cookie from 'cookie';
+
+// import our main App component
+import App from '../../src/App';
+
+import { getLinks } from '../sape';
+import { StaticRouter } from 'react-router-dom';
+
+const path = require('path');
+const fs = require('fs');
+
+const serverRenderer = async (req, res, next) => {
+
+ // point to the html file created by CRA's build tool
+ const filePath = path.resolve(__dirname, '..', '..', 'dist', 'index.html');
+
+ // links
+ const cookies = cookie.parse(req.headers.cookie || '');
+
+ const links = await getLinks(req.originalUrl, cookies['sape_cookie']);
+ console.log(`URL: ${req.originalUrl} LINKS: ${links.join(' ')}`);
+ fs.readFile(filePath, 'utf8', (err, htmlData) => {
+ if (err) {
+ console.error('err', err);
+ return res.status(404).end();
+ }
+
+ const routerContext = {};
+
+ // render the app as a string
+ const html = ReactDOMServer.renderToString(
+ <StaticRouter location={req.baseUrl} context={routerContext}>
+ <App footer={links.join(' ')}/>
+ </StaticRouter>
+ );
+
+ // inject the rendered app into our html and send it
+ return res.send(
+ htmlData.replace(
+ '<div id="app"></div>',
+ `<div id="app">${html}</div>`
+ )
+ );
+ });
+};
+
+export default serverRenderer;