Server Rendering

Rendering

An alternative to parsing an existing HTML string and rendering existing tags within it, is to create the component instance imperatively:

import WaferServer from "@lamplightdev/wafer/lib/server/wafer.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,
},
],
},
};
}
}

// create the element, passing in the tag name and the registry of components
const el = new MyExample(
{ tagName: "my-example" },
{
"my-example": {
def: MyExample,
},
}
);

// `construct` emulates the process of being constructed in a browser context
await el.construct();

// `connectedCallback` emulates the process of being attached to the DOM and
// runs any initial updates
await el.connectedCallback();

// update a property
el.firstname = "Alan";

// wait for the property targets to update
await el.updateDone();

and render it to a string which can then be sent in the response:

response.send(el.toString());

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

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

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

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: Hybrid Usage Previous: Parsing