Server Rendering

Parsing

Given a Wafer server component and an HTML string:

import WaferServer from "@lamplightdev/wafer/lib/server/wafer.js";
import { parse } from "@lamplightdev/wafer/lib/server/element.js";

class MyExample extends WaferServer {
static get template() {
return 'Hi <span id="firstname"></span>!';
}

static get props() {
return {
firstname: {
type: String,
targets: [
{
selector: "$#firstname",
text: true,
},
],
},
};
}
}

const htmlString = `
<div>
<h1>Greeting</h1>
<my-example firstname="Ada"></my-example>
</div>
`
;

a tree of HTML like nodes can be created using parse by passing in the HTML string and a registry of Wafer components with their tag names and definitions:

const tree = await parse(htmlString, {
"my-example": {
def: MyExample,
},
});

This tree can then be rendered as a string to send as a response to the client:

response.send(tree.toString());

This will result in the following HTML being sent and rendered in the browser (with no client side JavaScript required):

<div>
<h1>Greeting</h1>
<my-example name="Ada" wafer-ssr>
<template shadowroot="open"> Hi <span id="firstname">Ada</span>! </template>
</my-example>
</div>

Note that even un-reflected properties are shown as attributes. This is because attributes are used as the source of data when components are optionally rehydrated on the client when used in hybrid mode, along with the wafer-ssr attribute. This behaviour can be removed if the component is being used in server only mode.

Example

Open in new window

In this example an open declarative shadow root is being created since the component uses Shadow DOM by default, but the result can also be rendered into a closed shadow root or the Light DOM by specifying the shadow property in the constructor.

Wafer server component that render to the Shadow DOM make use of the Declarative Shadow DOM (DSD). Currently only Chromium based browsers support DSD, so in order to render Wafer server components on non-Chromium browsers a tiny polyfill is used.

Next: Rendering Previous: Introduction