Kofi
Kofi•13mo ago

Minimal code for Preact SSR

What's the actual code to do some Preact SSR with Deno? For example something simple like a counter that is incremented by 1 each seconds. Ideally something that could run on a Deno Deploy Playground without any deno.json
6 Replies
Deno AI Helper
Deno AI Helper•13mo ago
I'm sorry, but the documentation does not provide a specific example of server-side rendering (SSR) with Preact using Deno. However, it does mention that Fresh and Aleph.js are popular frameworks for developing React-like websites with Deno, and they use Preact as an alternative foundational technology to provide a better, more performant experience. For a more detailed guide on how to use these frameworks with Deno, you may want to refer to their respective documentation or look for specific tutorials online. Remember, when working with Deno, you have built-in TypeScript support, and you can use JavaScript modules from npm in your Deno programs with the "npm:" specifier in your imports. Please note that this information is not in the documentation, and it's always a good idea to refer to the official documentation of the tools you are using for the most accurate and up-to-date information. 🦕
marvinh.
marvinh.•13mo ago
/** @jsxImportSource https://esm.sh/preact */

import { renderToString } from "npm:preact-render-to-string";

function App() {
return <h1>hello world</h1>
}

Deno.serve(() => {
const html = renderToString(<App />);
return new Response(html, {
headers: {
"Content-Type": "text/html"
}
});
});
/** @jsxImportSource https://esm.sh/preact */

import { renderToString } from "npm:preact-render-to-string";

function App() {
return <h1>hello world</h1>
}

Deno.serve(() => {
const html = renderToString(<App />);
return new Response(html, {
headers: {
"Content-Type": "text/html"
}
});
});
Kofi
KofiOP•13mo ago
Thanks! Awesome. How about interactivity? If I add a button an a counter it won’t work. It’s some kind of server component. 1. Is hydration what I need? If yes, how to proceed? 2. Can it still be fine using only one file on the playground?
marvinh.
marvinh.•13mo ago
Event listeners only work in the browser, not in the server. To be able to make the server rendered HTML interactive in the browser you need to hydrate it on the client and be sure to ship the relevant components as JS to the browser as well.
Kofi
KofiOP•13mo ago
How does hydration work? I only heard about it
marvinh.
marvinh.•13mo ago
It's basically a faster variant of the typical render() function on the client that only attaches event listeners. That's really all there is to it.
// normal render
render(<App />, document.getElementById("app"))
// hydrate
hydrate(<App />, document.getElementbyId("app"));
// normal render
render(<App />, document.getElementById("app"))
// hydrate
hydrate(<App />, document.getElementbyId("app"));