Skip to content

Instantly share code, notes, and snippets.

@mstaicu
Last active May 2, 2026 21:01
Show Gist options
  • Select an option

  • Save mstaicu/503289174d375ca434641059698581fc to your computer and use it in GitHub Desktop.

Select an option

Save mstaicu/503289174d375ca434641059698581fc to your computer and use it in GitHub Desktop.
Remix Run v3
// package.json
{
"type": "module",
"scripts": {
"build": "esbuild app/pages/register.client.ts app/pages/login.client.ts --bundle --format=esm --outdir=public/assets --entry-names=[name] --minify --sourcemap && esbuild server.ts --bundle --platform=node --format=esm --outfile=dist/server.js --packages=external",
"dev": "esbuild app/pages/register.client.ts app/pages/login.client.ts --bundle --format=esm --outdir=public/assets --entry-names=[name] --sourcemap --watch & NODE_ENV=development tsx watch server.ts",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"remix": "^3.0.0-beta.0"
},
"devDependencies": {
"@types/node": "^25.6.0",
"esbuild": "^0.28.0",
"tsx": "^4.21.0",
"typescript": "^6.0.3"
}
}
// server.js
import http from "node:http";
import { createRouter } from "remix/fetch-router";
import { get, route } from "remix/fetch-router/routes";
import { html } from "remix/html-template";
import { createRequestListener } from "remix/node-fetch-server";
import { createHtmlResponse } from "remix/response/html";
const CONTENT_BASE_URL =
process.env.CONTENT_BASE_URL ?? "https://example.com/content";
const routes = route({
home: get("/"),
about: get("/about"),
});
const router = createRouter();
router.get(routes.home, () => renderPage("home"));
router.get(routes.about, () => renderPage("about"));
async function renderPage(slug) {
const page = await fetchPage(slug);
if (!page) {
return new Response("Not found", { status: 404 });
}
return createHtmlResponse(
html`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${page.title}</title>
<meta name="description" content="${page.description}" />
<style>
body {
margin: 0;
font-family: ui-sans-serif, system-ui, sans-serif;
color: #151515;
background: #ffffff;
}
header,
main {
width: min(100% - 32px, 960px);
margin-inline: auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding-block: 24px;
border-bottom: 1px solid #e5e5e5;
}
nav {
display: flex;
gap: 16px;
}
a {
color: inherit;
text-decoration: none;
font-weight: 600;
}
main {
padding-block: 72px;
}
h1 {
max-width: 760px;
margin: 0;
font-size: 56px;
line-height: 1;
}
p {
max-width: 680px;
font-size: 19px;
line-height: 1.65;
color: #444;
}
section {
margin-top: 48px;
}
h2 {
margin-bottom: 8px;
font-size: 28px;
}
</style>
</head>
<body>
<header>
<a href="/">Aperitif</a>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>
<h1>${page.title}</h1>
<p>${page.description}</p>
${page.sections
.map(
(section) => html`
<section>
<h2>${section.heading}</h2>
<p>${section.body}</p>
</section>
`,
)
.join("")}
</main>
</body>
</html>`,
{
headers: {
"Cache-Control": "public, max-age=60, stale-while-revalidate=300",
},
},
);
}
async function fetchPage(slug) {
const response = await fetch(`${CONTENT_BASE_URL}/pages/${slug}.json`, {
headers: { Accept: "application/json" },
});
if (response.status === 404) return null;
if (!response.ok) throw new Error(`CONTENT_FETCH_FAILED_${response.status}`);
return response.json();
}
const server = http.createServer(
createRequestListener((request) => router.fetch(request)),
);
const port = Number.parseInt(process.env.PORT ?? "3000", 10);
server.listen(port, () => {
console.log(`marketing site listening on http://localhost:${port}`);
});
@mstaicu
Copy link
Copy Markdown
Author

mstaicu commented May 2, 2026

{
  "title": "Modern SaaS Infrastructure",
  "description": "A short marketing description.",
  "sections": [
    {
      "heading": "Fast to launch",
      "body": "Content fetched from your CMS or content service."
    }
  ]
}

@mstaicu
Copy link
Copy Markdown
Author

mstaicu commented May 2, 2026

Next level:

// server.js
import http from "node:http";
import { createRouter } from "remix/fetch-router";
import { get, route } from "remix/fetch-router/routes";
import { html } from "remix/html-template";
import { createRequestListener } from "remix/node-fetch-server";
import { createHtmlResponse } from "remix/response/html";

const CONTENT_BASE_URL =
  process.env.CONTENT_BASE_URL ?? "https://example.com/content";

const PORT = Number.parseInt(process.env.PORT ?? "3000", 10);
const CACHE_TTL_MS = 60_000;

const routes = route({
  about: get("/about"),
  home: get("/"),
});

const router = createRouter();
const pageCache = new Map();

router.get(routes.home, () => renderMarketingPage("home"));
router.get(routes.about, () => renderMarketingPage("about"));

async function renderMarketingPage(slug) {
  try {
    const page = await getPage(slug);

    if (!page) {
      return renderNotFound();
    }

    return renderDocument({
      body: pageTemplate(page),
      description: page.description,
      status: 200,
      title: page.title,
    });
  } catch (error) {
    console.error(error);
    return renderDocument({
      body: html`
        <section class="hero">
          <p class="eyebrow">Unavailable</p>
          <h1>Content is temporarily unavailable.</h1>
          <p class="lead">Try again in a moment.</p>
        </section>
      `,
      description: "Content is temporarily unavailable.",
      status: 502,
      title: "Unavailable",
    });
  }
}

async function getPage(slug) {
  const cached = pageCache.get(slug);

  if (cached && cached.expiresAt > Date.now()) {
    return cached.page;
  }

  const page = await fetchPage(slug);

  pageCache.set(slug, {
    expiresAt: Date.now() + CACHE_TTL_MS,
    page,
  });

  return page;
}

async function fetchPage(slug) {
  const response = await fetch(`${CONTENT_BASE_URL}/pages/${slug}.json`, {
    headers: { Accept: "application/json" },
  });

  if (response.status === 404) return null;
  if (!response.ok) throw new Error(`CONTENT_FETCH_FAILED_${response.status}`);

  const page = await response.json();

  return normalizePage(page);
}

function normalizePage(page) {
  return {
    description: String(page.description ?? ""),
    sections: Array.isArray(page.sections)
      ? page.sections.map((section) => ({
          body: String(section.body ?? ""),
          heading: String(section.heading ?? ""),
        }))
      : [],
    title: String(page.title ?? "Untitled"),
  };
}

function pageTemplate(page) {
  return html`
    <section class="hero">
      <p class="eyebrow">Aperitif</p>
      <h1>${page.title}</h1>
      <p class="lead">${page.description}</p>
    </section>

    <section class="sections">
      ${page.sections
        .map(
          (section) => html`
            <article>
              <h2>${section.heading}</h2>
              <p>${section.body}</p>
            </article>
          `,
        )
        .join("")}
    </section>
  `;
}

function renderNotFound() {
  return renderDocument({
    body: html`
      <section class="hero">
        <p class="eyebrow">404</p>
        <h1>Page not found.</h1>
        <p class="lead">The page you requested does not exist.</p>
      </section>
    `,
    description: "Page not found.",
    status: 404,
    title: "Page not found",
  });
}

function renderDocument({ body, description, status, title }) {
  return createHtmlResponse(
    html`<!doctype html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>${title}</title>
          <meta name="description" content="${description}" />
          <style>
            :root {
              color-scheme: light;
              font-family: Inter, ui-sans-serif, system-ui, sans-serif;
              color: #161616;
              background: #ffffff;
            }

            body {
              margin: 0;
            }

            header,
            main {
              width: min(100% - 32px, 1080px);
              margin-inline: auto;
            }

            header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding-block: 24px;
              border-bottom: 1px solid #e8e8e8;
            }

            nav {
              display: flex;
              gap: 18px;
            }

            a {
              color: inherit;
              text-decoration: none;
              font-weight: 650;
            }

            main {
              padding-block: 72px;
            }

            .hero {
              max-width: 820px;
            }

            .eyebrow {
              margin: 0 0 14px;
              color: #6b5a44;
              font-size: 13px;
              font-weight: 800;
              letter-spacing: 0.08em;
              text-transform: uppercase;
            }

            h1 {
              margin: 0;
              font-size: 64px;
              line-height: 0.95;
            }

            .lead {
              margin-top: 24px;
              max-width: 720px;
              color: #444;
              font-size: 20px;
              line-height: 1.65;
            }

            .sections {
              display: grid;
              grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
              gap: 28px;
              margin-top: 64px;
            }

            article {
              border-top: 1px solid #e8e8e8;
              padding-top: 24px;
            }

            h2 {
              margin: 0 0 10px;
              font-size: 24px;
            }

            article p {
              margin: 0;
              color: #4b4b4b;
              line-height: 1.7;
            }

            @media (max-width: 640px) {
              header {
                align-items: flex-start;
                flex-direction: column;
                gap: 16px;
              }

              h1 {
                font-size: 44px;
              }

              main {
                padding-block: 48px;
              }
            }
          </style>
        </head>
        <body>
          <header>
            <a href="/">Aperitif</a>
            <nav aria-label="Main navigation">
              <a href="/">Home</a>
              <a href="/about">About</a>
            </nav>
          </header>
          <main>${body}</main>
        </body>
      </html>`,
    {
      headers: {
        "Cache-Control": "public, max-age=60, stale-while-revalidate=300",
      },
      status,
    },
  );
}

const server = http.createServer(
  createRequestListener((request) => router.fetch(request)),
);

server.listen(PORT, () => {
  console.log(`marketing site listening on http://localhost:${PORT}`);
});

@mstaicu
Copy link
Copy Markdown
Author

mstaicu commented May 2, 2026

Next next next level

// server.jsx
// @jsxRuntime classic
// @jsx createElement

import http from "node:http";
import { createRouter } from "remix/fetch-router";
import { get, route } from "remix/fetch-router/routes";
import { createRequestListener } from "remix/node-fetch-server";
import { createElement, css } from "remix/ui";
import { renderToStream } from "remix/ui/server";
import { RMX_01 } from "remix/ui/theme";
import { Button } from "remix/ui/button";

const CONTENT_BASE_URL =
  process.env.CONTENT_BASE_URL ?? "https://example.com/content";

const PORT = Number.parseInt(process.env.PORT ?? "3000", 10);
const CACHE_TTL_MS = 60_000;

const routes = route({
  about: get("/about"),
  home: get("/"),
});

const router = createRouter();
const cache = new Map();

router.get(routes.home, () => renderPage("home"));
router.get(routes.about, () => renderPage("about"));

async function renderPage(slug) {
  try {
    const page = await getPage(slug);

    if (!page) {
      return renderDocument({
        page: {
          description: "Page not found.",
          sections: [],
          title: "Page not found",
        },
        status: 404,
      });
    }

    return renderDocument({ page, status: 200 });
  } catch (error) {
    console.error(error);

    return renderDocument({
      page: {
        description: "Content is temporarily unavailable.",
        sections: [],
        title: "Content unavailable",
      },
      status: 502,
    });
  }
}

function renderDocument({ page, status }) {
  return new Response(renderToStream(<Document page={page} />), {
    headers: {
      "Cache-Control":
        status === 200
          ? "public, max-age=60, stale-while-revalidate=300"
          : "no-store",
      "Content-Type": "text/html; charset=utf-8",
    },
    status,
  });
}

async function getPage(slug) {
  const cached = cache.get(slug);

  if (cached && cached.expiresAt > Date.now()) {
    return cached.page;
  }

  const response = await fetch(`${CONTENT_BASE_URL}/pages/${slug}.json`, {
    headers: { Accept: "application/json" },
  });

  if (response.status === 404) return null;
  if (!response.ok) throw new Error(`CONTENT_FETCH_FAILED_${response.status}`);

  const page = normalizePage(await response.json());

  cache.set(slug, {
    expiresAt: Date.now() + CACHE_TTL_MS,
    page,
  });

  return page;
}

function normalizePage(page) {
  return {
    description: String(page.description ?? ""),
    sections: Array.isArray(page.sections)
      ? page.sections.map((section) => ({
          body: String(section.body ?? ""),
          heading: String(section.heading ?? ""),
        }))
      : [],
    title: String(page.title ?? "Untitled"),
  };
}

function Document({ page }) {
  return (
    <html lang="en">
      <head>
        <RMX_01 />
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>{page.title}</title>
        <meta name="description" content={page.description} />
      </head>
      <body mix={bodyStyle}>
        <Header />
        <main mix={mainStyle}>
          <Hero page={page} />
          <Sections sections={page.sections} />
        </main>
      </body>
    </html>
  );
}

function Header() {
  return (
    <header mix={headerStyle}>
      <a href="/" mix={brandStyle}>
        Aperitif
      </a>
      <nav aria-label="Main navigation" mix={navStyle}>
        <a href="/">Home</a>
        <a href="/about">About</a>
      </nav>
    </header>
  );
}

function Hero({ page }) {
  return (
    <section mix={heroStyle}>
      <p mix={eyebrowStyle}>Aperitif</p>
      <h1 mix={titleStyle}>{page.title}</h1>
      <p mix={leadStyle}>{page.description}</p>
      <p>
        <Button tone="primary">Start a conversation</Button>
      </p>
    </section>
  );
}

function Sections({ sections }) {
  if (sections.length === 0) return null;

  return (
    <section mix={sectionsStyle}>
      {sections.map((section) => (
        <article key={section.heading} mix={articleStyle}>
          <h2>{section.heading}</h2>
          <p>{section.body}</p>
        </article>
      ))}
    </section>
  );
}

const bodyStyle = css({
  margin: 0,
  backgroundColor: "#ffffff",
  color: "#151515",
  fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif",
});

const headerStyle = css({
  alignItems: "center",
  borderBottom: "1px solid #e7e7e7",
  display: "flex",
  justifyContent: "space-between",
  marginInline: "auto",
  paddingBlock: "24px",
  width: "min(100% - 32px, 1080px)",
  "@media (max-width: 640px)": {
    alignItems: "flex-start",
    flexDirection: "column",
    gap: "16px",
  },
});

const brandStyle = css({
  color: "inherit",
  fontWeight: 750,
  textDecoration: "none",
});

const navStyle = css({
  display: "flex",
  gap: "18px",
  "& a": {
    color: "inherit",
    fontWeight: 650,
    textDecoration: "none",
  },
});

const mainStyle = css({
  marginInline: "auto",
  paddingBlock: "72px",
  width: "min(100% - 32px, 1080px)",
});

const heroStyle = css({
  maxWidth: "820px",
});

const eyebrowStyle = css({
  color: "#6b5a44",
  fontSize: "13px",
  fontWeight: 800,
  letterSpacing: "0.08em",
  margin: "0 0 14px",
  textTransform: "uppercase",
});

const titleStyle = css({
  fontSize: "64px",
  lineHeight: "0.95",
  margin: 0,
  "@media (max-width: 640px)": {
    fontSize: "44px",
  },
});

const leadStyle = css({
  color: "#444",
  fontSize: "20px",
  lineHeight: "1.65",
  marginTop: "24px",
  maxWidth: "720px",
});

const sectionsStyle = css({
  display: "grid",
  gap: "28px",
  gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
  marginTop: "64px",
});

const articleStyle = css({
  borderTop: "1px solid #e7e7e7",
  paddingTop: "24px",
  "& h2": {
    fontSize: "24px",
    margin: "0 0 10px",
  },
  "& p": {
    color: "#4b4b4b",
    lineHeight: "1.7",
    margin: 0,
  },
});

const server = http.createServer(
  createRequestListener((request) => router.fetch(request)),
);

server.listen(PORT, () => {
  console.log(`marketing site listening on http://localhost:${PORT}`);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment