Skip to content

Instantly share code, notes, and snippets.

@jonathanhudak
Created March 18, 2022 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanhudak/d64e502d12ca7a201ac9438ca683e940 to your computer and use it in GitHub Desktop.
Save jonathanhudak/d64e502d12ca7a201ac9438ca683e940 to your computer and use it in GitHub Desktop.
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.ns.d.ts" />
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.fetchevent.d.ts" />
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.window.d.ts" />
/*
Reference
* https://strapi.io/blog/rendering-react-ssr-with-deno-and-deno-deploy
*/
import * as React from "https://esm.sh/react@17.0.2";
import * as ReactDOMServer from "https://esm.sh/react-dom@17.0.2/server";
import { createElement as h } from "https://esm.sh/react@17.0.2";
interface Message {
message: string;
}
interface Book {
title: string;
}
interface AppData {
messages: Message[];
books: Book[];
title: string;
}
interface Props {
data: AppData;
}
function App({ data }: Props) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<title>{data.title}</title>
</head>
<body>
<div className="container">
<h1>{data.title}</h1>
<section>
<h2>Messages</h2>
{data.messages.map(({ message }) => (
<p key={message}>{message}</p>
))}
</section>
</div>
</body>
</html>
);
}
const API_BASE_URL = "https://hello-heron-api.deno.dev";
async function getData(path: string) {
const response = await fetch(`${API_BASE_URL}${path}`, {
headers: {
"Content-Type": "application/json",
},
});
return response.json();
}
addEventListener("fetch", async (event: FetchEvent) => {
// Fetch data.
const data = await getData("");
// Render React components to a string.
const str = ReactDOMServer.renderToString(<App data={data} />);
// Prepend the DOCTYPE for better compatibility.
const body = `<!DOCTYPE html>${str}`;
const response = new Response(body, {
headers: { "content-type": "text/html; charset=utf-8" },
});
event.respondWith(response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment