# Server islands

> Ship a static sitelo site and mount a Node host that renders islands at request time.

sitelo builds static HTML. Server islands fill in the bits that must be fresh — a clock, comments, stock, anything that needs the request. This recipe builds a page with a time island, then runs a small Node server that serves `dist/` and `/_sitelo/islands`.

A copy of this project lives in the sitelo repo under `examples/islands/`.

## What you get

- A static home page with an island placeholder and fallback HTML
- A server-only island module under `src/islands/` that never ships to the browser
- A client loader that swaps in the fragment from `/_sitelo/islands/<name>`
- A production-shaped `server.js` — static files + `createIslandsNodeHandler`

## Project layout

`project`

```bash
my-site/
  sitelo.config.js
  server.js              # Node host: static dist + islands
  netlify.toml           # Netlify rewrite → function
  vercel.json            # Vercel rewrite → api route
  package.json
  netlify/functions/
    islands.mjs          # Netlify islands handler
  api/islands/
    [...path].js         # Vercel islands handler
  src/
    index.ht.js          # page with an island placeholder
    js/
      islands.js         # client loader (bundled into dist/)
    islands/
      time.js            # server-only fragment module
    css/
      styles.css
```

`sitelo.config.js`

```javascript
export default {
  site: 'https://example.com',
}
```

## Island module

Plain `.js` (not `.ht.js`). Receives `{ name, props, request }` and returns an HTML string. This one uses the request time and user-agent so you can see it’s rendered per request.

`src/islands/time.js`

```javascript
import { escapeHtml } from 'sitelo/page'

export default function time({ props, request }) {
  const label = typeof props?.label === 'string' ? props.label : 'Server time'
  const now = new Date().toISOString()
  const ua = request?.headers?.get?.('user-agent') ?? 'unknown'

  return `
    <p><strong>${escapeHtml(label)}:</strong> <time datetime="${now}">${now}</time></p>
    <p class="muted">Rendered on request for <code>${escapeHtml(ua.slice(0, 48))}</code></p>
  `
}
```

## Place the island on a page

`island()` embeds props in the placeholder. The build ships the fallback; the loader replaces it when the endpoint responds.

`src/index.ht.js — Template literal`

```javascript
import { island } from 'sitelo/islands'

export default () => `
  <html lang="en">
    <head>
      <title>Server islands demo</title>
      <link rel="stylesheet" href="/css/styles.css">
    </head>
    <body>
      <h1>Static page, live island</h1>
      <p>This HTML was built once. The box below is filled at request time.</p>
      ${island(
        'time',
        { label: 'Right now' },
        '<p>Loading server time…</p>',
      )}
      <script type="module" src="/js/islands.js"></script>
    </body>
  </html>
`
```

`src/index.ht.js — ht.js (recommended)`

```javascript
import { html, head, title, link, body, h1, p, script } from 'javascript-to-html'
import { island } from 'sitelo/islands'

export default () =>
  html({ lang: 'en' },
    head(
      title('Server islands demo'),
      link({ rel: 'stylesheet', href: '/styles.css' }),
    ),
    body(
      h1('Static page, live island'),
      p('This HTML was built once. The box below is filled at request time.'),
      island(
        'time',
        { label: 'Right now' },
        '<p>Loading server time…</p>',
      ),
      script({ type: 'module', src: '/islands.js' }),
    ),
  )
```

`src/index.ht.jsx — JSX`

```jsx
import { island } from 'sitelo/islands'

export default function Home() {
  return (
    <html lang="en">
      <head>
        <title>Server islands demo</title>
        <link rel="stylesheet" href="/css/styles.css" />
      </head>
      <body>
        <h1>Static page, live island</h1>
        <p>This HTML was built once. The box below is filled at request time.</p>
        {island(
          'time',
          { label: 'Right now' },
          '<p>Loading server time…</p>',
        )}
        <script type="module" src="/js/islands.js" />
      </body>
    </html>
  )
}
```

## Client loader

`src/js/islands.js`

```javascript
import { mountIslands } from 'sitelo/islands/client'

mountIslands()
```

`src/css/styles.css`

```css
body {
  font-family: system-ui, sans-serif;
  max-width: 36rem;
  margin: 2rem auto;
  padding: 0 1rem;
  line-height: 1.5;
}

[data-sitelo-island] {
  margin: 1.5rem 0;
  padding: 1rem 1.25rem;
  border: 1px solid #ccc;
}

[data-sitelo-island-state='loading'] {
  opacity: 0.7;
}

.muted {
  color: #666;
  font-size: 0.9rem;
}
```

## Node host

After `sitelo build`, this process serves `dist/` and renders islands with `createIslandsNodeHandler` from `sitelo/islands/server`. Island modules stay out of `dist/` — the host imports them from `src/`.

`server.js`

```javascript
import fs from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createIslandsFromDirectory, createIslandsNodeHandler } from 'sitelo/islands/server'

const root = path.dirname(fileURLToPath(import.meta.url))
const dist = path.join(root, 'dist')
const port = Number(process.env.PORT) || 3000

const handleIslands = createIslandsNodeHandler({
  islands: createIslandsFromDirectory(path.join(root, 'src/islands')),
})

const MIME = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
  '.xml': 'application/xml',
  '.json': 'application/json',
}

function sendFile(res, filePath) {
  const ext = path.extname(filePath)
  res.statusCode = 200
  res.setHeader('Content-Type', MIME[ext] ?? 'application/octet-stream')
  fs.createReadStream(filePath).pipe(res)
}

function resolveStatic(urlPath) {
  const clean = decodeURIComponent(urlPath.split('?')[0])
  const relative = clean === '/' ? 'index.html' : clean.replace(/^\/+/, '')
  const candidate = path.normalize(path.join(dist, relative))

  if (!candidate.startsWith(dist + path.sep) && candidate !== dist) {
    return null
  }
  if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
    return candidate
  }

  const asIndex = path.join(candidate, 'index.html')
  if (fs.existsSync(asIndex) && fs.statSync(asIndex).isFile()) {
    return asIndex
  }

  return null
}

const server = http.createServer(async (req, res) => {
  await handleIslands(req, res, () => {
    const file = resolveStatic(req.url ?? '/')
    if (file) {
      sendFile(res, file)
      return
    }

    const notFound = path.join(dist, '404.html')
    res.statusCode = 404
    if (fs.existsSync(notFound)) {
      sendFile(res, notFound)
    } else {
      res.setHeader('Content-Type', 'text/plain; charset=utf-8')
      res.end('Not found')
    }
  })
})

server.listen(port, () => {
  console.log(`Listening on http://localhost:${port}`)
})
```

## Build and run

`shell`

```bash
npm install
sitelo build
node server.js
```

Open `http://localhost:3000`. You should see the fallback briefly, then the server time. Hit refresh — the timestamp changes. In `sitelo` (dev) and `sitelo preview` you don’t need `server.js`: the CLI already serves `/_sitelo/islands`.

## Deploy

This example ships host stubs next to the Node server:

- `Node` — `npm run build && npm start` (set `PORT` on the platform). Uses `createIslandsFromDirectory`.
- `Netlify` — `netlify.toml` rewrites `/_sitelo/islands/*` to `netlify/functions/islands.mjs`.
- `Vercel` — `vercel.json` rewrites to `api/islands/[...path].js`.
- Static-only hosts (GitHub Pages, plain S3) — placeholders keep their fallback until you add a function.

For serverless or edge elsewhere, use `createIslandsHandler` (web `Request` → `Response`) — see the [Server islands docs](https://sitelo.dev/docs/islands). Point `mountIslands({ endpoint })` at that function’s URL if it isn’t same-origin.

## Notes

### Static hosts alone

GitHub Pages, plain S3, and similar hosts have no server process. Without an islands endpoint the fallback HTML simply stays — pages still work, just without the live fragment.

### Keep props small

Props travel in the HTML attribute and the request query string. Don’t put secrets or large payloads there — fetch those inside the island module on the server.

[Server islands docs](https://sitelo.dev/docs/islands) · [Basic site / deploy](https://sitelo.dev/examples/basic) · [All examples](https://sitelo.dev/examples)
