-
Notifications
You must be signed in to change notification settings - Fork 11
Using can ssr
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):
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));
}
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 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.
The tests contain several example projects:
- A DoneJS app using done-autorender
- A DoneJS app using a plain JavaScript file for its main
- A jQuery app
- A React app