Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Prerender data API #141

Merged
merged 3 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading