Skip to content

Commit

Permalink
feat: Prerender data API (#141)
Browse files Browse the repository at this point in the history
* feat: Add back prerender data API

* test: Add tests for prerender data API

* docs: Add docs for prerender data API
  • Loading branch information
rschristian authored Sep 2, 2024
1 parent 3a48c70 commit 6a0d734
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ export async function prerender(data) {
// Optionally add additional links that should be
// prerendered (if they haven't already been)
links: new Set([...discoveredLinks, '/foo', '/bar']),
// Optional data to serialize into a script tag for use on the client:
// <script type="application/json" id="preact-prerender-data">{"url":"/"}</script>
data: { url: data.url },
// Optionally configure and add elements to the `<head>` of
// the prerendered HTML document
head: {
Expand Down
3 changes: 2 additions & 1 deletion demo/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ if (typeof window !== "undefined") {
hydrate(<App />, document.getElementById("app"));
}

export async function prerender() {
export async function prerender(data) {
const { html, links } = await ssr(<App />);
return {
html,
links,
data: { url: data.url },
head: {
lang: "en",
title: "Prerendered Preact App",
Expand Down
5 changes: 5 additions & 0 deletions src/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,11 @@ export function PrerenderPlugin({
if (result.head) {
head = result.head;
}
if (result.data) {
body += `<script type="application/json" id="preact-prerender-data">${JSON.stringify(
result.data,
)}</script>`;
}
} else {
body = result;
}
Expand Down
6 changes: 6 additions & 0 deletions test/build.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ test("builds demo successfully", async () => {
assert.match(outputHtml, /<title>Prerendered Preact App<\/title>/);
assert.match(outputHtml, /<meta name="description" content="This is a prerendered Preact app">/);

// Prerender Data
assert.match(
outputHtml,
/<script type="application\/json" id="preact-prerender-data">{"url":"\/"}<\/script>/
);

// Local Fetch
assert.match(outputHtml, /Local fetch works/);

Expand Down

0 comments on commit 6a0d734

Please sign in to comment.