File size: 1,179 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { join } from 'path';
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { getServerState } from 'react-instantsearch-hooks-server';
import App from './App';

const app = express();

app.use('/assets', express.static(join(__dirname, 'assets')));

app.get('/', async (req, res) => {
  const location = new URL(
    `${req.protocol}://${req.get('host')}${req.originalUrl}`
  );
  const serverState = await getServerState(<App location={location} />, {
    renderToString,
  });
  const html = renderToString(
    <App serverState={serverState} location={location} />
  );

  res.send(
    `<!DOCTYPE html>
<html>
  <head>
    <title>React InstantSearch SSR</title>
    <link href="https://cdn.jsdelivr.net/npm/instantsearch.css@7/themes/satellite-min.css" rel="stylesheet" />
    <script>window.__SERVER_STATE__ = ${JSON.stringify(serverState)}</script>
  </head>
  
  <body>
    <div id="root">${html}</div>
  </body>
  
  <script src="/assets/bundle.js"></script>
</html>`
  );
});

app.listen(8080, () => {
  // eslint-disable-next-line no-console
  console.log('Listening on: http://localhost:8080');
});