Server-Side Rendering (SSR) SSR is now possible with the provided onServerDefine and insertTemplates functions.
  • onServerDefine() lets you pass a callback that runs each time a custom element is defined on the server. When an element is defined on the server, its render function will run once to get its initial HTML, which will then trigger this callback. Assuming you configured the element to use shadow DOM, this will render declarative shadow DOM template tags, using the same options.
  • insertTemplates() takes the tag name and inner HTML of the custom element and inserts it into the provided HTML string, parsing any variables that could not be resolved upon defining, (e.g. attributes).
import { onServerDefine, insertTemplates } from 'thunderous'; let htmlResponse = ` <!DOCTYPE html> <html lang="en"> <head> <title>Example</title> </head> <body> <my-element></my-element> </body> </html> `; onServerDefine((tagName, innerHTML) => { htmlResponse = insertTemplates(tagName, innerHTML, htmlResponse); }); export default function handler(req, res) { // ----- define custom elements here res.setHeader('Content-Type', 'text/html'); res.send(htmlResponse); } Introducing server compatibility also opens up a host of new potential errors, mainly as a result of accessing client-side APIs on the server. To avoid these errors, you can use the clientOnlyCallback() function to conditionally run code only on the client. This is provided in the arguments of the render callback passed to customElement(), but can also be imported directly from the library. These two methods have distinct use cases - pay close attention to the comments in the code snippet below. import { customElement, html } from 'thunderous'; const MyElement = customElement(({ clientOnlyCallback }) => { // This will be run in the constructor of the custom element. clientOnlyCallback(() => { console.log('This will only run on the client.'); }); return html`<div>My Element</div>`; }); // ------ OR ------ import { clientOnlyCallback } from 'thunderous'; // This will run immediately, and may be awaited if necessary. clientOnlyCallback(() => { console.log('This will only run on the client.'); });