import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { DataProvider, createDataClient } from 'react-isomorphic-data';
import { getDataFromTree } from 'react-isomorphic-data/ssr';
import fetch from 'node-fetch';
import App from './App';
global.fetch = fetch;
const server = express();
server.get('/*', async (req: express.Request, res: express.Response) => {
const dataClient = createDataClient({
initialCache: {},
ssr: true,
headers: {
'cookie': req.header('cookie'),
'my-custom-header': 'will be sent on all requests',
}});
const reactApp = (
<DataProvider client={dataClient}>
<App />
</DataProvider>
);
try {
await getDataFromTree(reactApp);
} catch (err) {
console.error('Error while trying to getDataFromTree', err);
}
const markup = renderToString(reactApp);
res.send(
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charSet='utf-8' />
<title>Razzle TypeScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
window.__cache=${JSON.stringify(dataClient.cache)}
</script>
</head>
<body>
<div id="root">${markup}</div>
</body>
</html>`
);
});