Island server
In questa pagina
sitelo costruisce HTML statico. Le island server riempiono le parti che devono essere fresche — un orologio, i commenti, la disponibilità, tutto ciò che ha bisogno della richiesta. Questa ricetta costruisce una pagina con un’island dell’ora, poi avvia un piccolo server Node che serve dist/ e /_sitelo/islands.
Una copia di questo progetto si trova nel repository di sitelo sotto examples/islands/.
Cosa ottieni
- Una home page statica con un segnaposto per l’island e l’HTML di riserva
- Un modulo island destinato solo al server sotto
src/islands/, che non arriva mai al browser - Un loader client che sostituisce il frammento preso da
/_sitelo/islands/<nome> - Un
server.jscon la forma della produzione — file statici +createIslandsNodeHandler
Struttura del progetto
my-site/
sitelo.config.js
server.js # Host Node: dist statico + island
netlify.toml # rewrite Netlify → function
vercel.json # rewrite Vercel → route api
package.json
netlify/functions/
islands.mjs # handler island per Netlify
api/islands/
[...path].js # handler island per Vercel
src/
index.ht.js # pagina con un segnaposto island
js/
islands.js # loader client (incluso nel bundle in dist/)
islands/
time.js # modulo frammento solo lato server
css/
styles.cssexport default {
site: 'https://example.com',
}1. Modulo island
Un semplice .js (non .ht.js). Riceve { name, props, request } e restituisce una stringa HTML. Questo usa l’ora della richiesta e lo user-agent, così vedi che viene renderizzato a ogni richiesta.
export default function time({ props, request }) {
const label = typeof props?.label === 'string' ? props.label : 'Ora del server'
const now = new Date().toISOString()
const ua = request?.headers?.get?.('user-agent') ?? 'unknown'
return `
<p><strong>${label}:</strong> <time datetime="${now}">${now}</time></p>
<p class="muted">Renderizzato su richiesta per <code>${escapeHtml(ua.slice(0, 48))}</code></p>
`
}
function escapeHtml(value) {
return value
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
}2. Metti l’island in una pagina
island() incorpora le props nel segnaposto. La build pubblica il contenuto di riserva; il loader lo sostituisce quando l’endpoint risponde.
import { island } from 'sitelo/islands'
export default () => `
<html lang="it">
<head>
<title>Demo di island server</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Pagina statica, island viva</h1>
<p>Questo HTML è stato costruito una volta sola. Il riquadro qui sotto viene riempito al momento della richiesta.</p>
${island(
'time',
{ label: 'Adesso' },
'<p>Caricamento dell’ora del server…</p>',
)}
<script type="module" src="/js/islands.js"></script>
</body>
</html>
`import { html, head, title, link, body, h1, p, script } from 'javascript-to-html'
import { island } from 'sitelo/islands'
export default () =>
html({ lang: 'it' },
head(
title('Demo di island server'),
link({ rel: 'stylesheet', href: '/styles.css' }),
),
body(
h1('Pagina statica, island viva'),
p('Questo HTML è stato costruito una volta sola. Il riquadro qui sotto viene riempito al momento della richiesta.'),
island(
'time',
{ label: 'Adesso' },
'<p>Caricamento dell’ora del server…</p>',
),
script({ type: 'module', src: '/islands.js' }),
),
)import { island } from 'sitelo/islands'
export default function Home() {
return (
<html lang="it">
<head>
<title>Demo di island server</title>
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body>
<h1>Pagina statica, island viva</h1>
<p>Questo HTML è stato costruito una volta sola. Il riquadro qui sotto viene riempito al momento della richiesta.</p>
{island(
'time',
{ label: 'Adesso' },
'<p>Caricamento dell’ora del server…</p>',
)}
<script type="module" src="/js/islands.js" />
</body>
</html>
)
}3. Loader client
import { mountIslands } from 'sitelo/islands/client'
mountIslands()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;
}4. Host Node
Dopo sitelo build, questo processo serve dist/ e renderizza le island con createIslandsNodeHandler da sitelo/islands/server. I moduli island restano fuori da dist/ — l’host li importa da src/.
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('Non trovato')
}
})
})
server.listen(port, () => {
console.log(`In ascolto su http://localhost:${port}`)
})5. Build ed esecuzione
npm install
sitelo build
node server.jsApri http://localhost:3000. Dovresti vedere per un attimo il contenuto di riserva, poi l’ora del server. Ricarica — l’orario cambia. Con sitelo (sviluppo) e sitelo preview non ti serve server.js: la CLI serve già /_sitelo/islands.
Deploy
Questo esempio porta con sé degli stub di host accanto al server Node:
Node—npm run build && npm start(impostaPORTsulla piattaforma). UsacreateIslandsFromDirectory.Netlify—netlify.tomlriscrive/_sitelo/islands/*versonetlify/functions/islands.mjs.Vercel—vercel.jsonriscrive versoapi/islands/[...path].js.- Host solo statici (GitHub Pages, S3 puro) — i segnaposto si tengono il contenuto di riserva finché non aggiungi una funzione.
Per serverless o edge altrove, usa createIslandsHandler (Request web → Response) — vedi la documentazione sulle island server. Punta mountIslands({ endpoint }) all’URL di quella funzione se non è della stessa origine.
Note
Host solo statici
GitHub Pages, S3 puro e host simili non hanno un processo server. Senza un endpoint per le island l’HTML di riserva semplicemente resta — le pagine funzionano lo stesso, solo senza il frammento dal vivo.
Tieni le props piccole
Le props viaggiano nell’attributo HTML e nella query string della richiesta. Non metterci segreti o carichi grossi — recuperali dentro il modulo island, sul server.
Documentazione sulle island server · Sito di base / deploy · Tutti gli esempi