Headless SSR via
JSS supports headless server-side rendering using any service that supports hosting Node.js applications. In this technique the JSS app receives an incoming HTTP request, which is then rewritten and proxied into a Layout Service request to a Sitecore server. The reply from Layout Service is then provided to the app's SSR infrastructure to render to HTML, the same way that Integrated Mode would work within Sitecore, and then finally the resultant HTML is returned to the client.
All Sitecore marketing features are supported by this headless mode, including personalization, tracking, multivariate testing, etc.
How to use
Clone the JSS samples repository and copy the
samples/node-headless-ssr-proxyfolder to your disk, for example:
This sample app acts as a HTTP proxy to the Sitecore server, proxying incoming requests to Layout Service, and then rendering the resultant JSON to HTML before returning it. The app is heavily commented.
/config.jsfile and set
apiHostto your Sitecore instance host and the
apiKeyto your SSC API Key (see server setup if you don't have an API key yet)
Create a production build of your app with
jss build. Ensure that the
layoutServiceHostin the app's
scjssconfig.jsonis set to the hostname of the
node-headless-ssr-proxyproxy (not directly to Sitecore). For local testing, this would default to
http://localhost:3000. In production, it would likely be something like
https://www.mysite.com. It is also possible to make requests directly to Sitecore, if you do not wish to run everything through the reverse proxy. Proxying the data APIs has the advantage of allowing Sitecore to live behind a firewall.
Copy the production build artifacts from your app to the proxy (i.e.
/node-headless-ssr-proxy/dist/MyApp). The path copied to should match the relative path that is set in the
sitecoreDistPathconfig in the app's
/dist/MyAppin the previous example).
index.jsand modify the bundle import to import your app's
server.bundle.jsfile that was just copied in:
const app = require('./dist/JssReactWeb/server.bundle');
Open a command prompt in your
node-headless-ssr-proxyfolder, and run
npm run start.
The console should show
server listening on port 3000!. To test, browse to
http://localhost:3000/and you should see the same app rendering now in the headless configuration.