Skip to content
Matthew Phillips edited this page Feb 11, 2016 · 8 revisions

can-ssr is able to handle server-side rendering of your application by loading it in a custom module loader based on StealJS. In order to work can-ssr expects a couple of functions to be implemented by your application's main (defined in your package.json). These functions look like (note that the examples are in ES6, but all formats are supported):

main.js

import initApp from './init';

export function createState(request) {
  return { 
    page: request.url.split("/").pop()
  };
}

export function render(document, state) {
  let title = document.createElement("title");
  title.appendChild(document.createTextNode("Hello world"));
  document.head.appendChild(title);

  document.body.appendChild(initApp(state));
}

createState

The main must either export a createState function which receives a request object and returns a state object. What type of object depends on the framework you are using, but this is an object that represents the application state for a given url.

render

render is a function that receives a document (which looks just like window.document and the state object created in createState.

Render can do whatever is needed to render the application and insert the result into the document. You can manipulate the document.head to insert a title, mount your app to a particular element in the body, or anything else.

render doesn't have a return value, can-ssr will know when the app is finished rendering and will serialize the entire document into a string.

Examples

The tests contain several example projects:

Clone this wiki locally