Elide sirve HTTP desde un manejador fetch o desde node:http; esta página crea un mismo servicio de las dos formas.
Para un servicio nuevo, empiece por Dos formas de servir, que no necesita paquetes. Para una aplicación existente basada en un framework, revise la tabla siguiente antes de instalar dependencias.
Frameworks
Comprobado con Elide 1.6.2:
| Framework | Compatibilidad | Siguiente paso |
|---|---|---|
| Hono 4.13.16 | Las rutas y JSON funcionan con un manejador fetch. | Siga el ejemplo de Hono. |
| Express 5.3.0 | Parcial: funcionan las rutas, res.json, express.raw() y la lectura manual del cuerpo; express.json() y express.text() detienen el proceso con TypeError: Buffer.. |
Lea el cuerpo manualmente o use express.raw(); consulte Análisis del cuerpo en Express. |
| Fastify 5.12.8 | Falla al importar: Error: No such built-in module: node:http2. |
Use un manejador fetch o node:http; consulte módulos integrados ausentes. |
Para módulos de Node concretos, consulte la Visión general de la API. Ejecute las pruebas de su aplicación y envíe peticiones a través de su middleware antes de migrar un servicio.
Dos formas de servir
| Manejador fetch | node:http |
|
|---|---|---|
| Entrada | export default { fetch } o Elide.serve({ fetch }) |
http. |
| Petición y respuesta | Request, Response de la Web |
IncomingMessage, ServerResponse |
| HTTPS y HTTP/2 | Opciones cert y key |
No disponible |
--contexts |
Sí | No; la segunda copia falla con EADDRINUSE |
// server.ts
export default {
port: Number(process.env.PORT ?? 3000),
fetch(request: Request): Response {
return new Response("hello\n");
},
};
// node-server.ts
import { createServer } from "node:http";
const port = Number(process.env.PORT ?? 3000);
createServer((req, res) => {
res.writeHead(200, { "content-type": "text/plain" });
res.end("hello\n");
}).listen(port, "127.0.0.1");
elide run server.ts
Mantenga el servidor en ejecución y envíe una petición desde una segunda terminal:
curl -i http://127.0.0.1:3000/
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
content-length: 6
server: elide
date: Sat, 10 Oct 2026 00:18:12 GMT
hello
elide run node-server.ts responde a la misma petición con Transfer-Encoding: chunked y Connection: keep-alive.
Si el puerto está ocupado, consulte Puerto ya en uso.
Dónde escucha cada estilo cuando no se indica una dirección:
| Servidor | Dirección predeterminada |
|---|---|
export default { fetch } con elide run |
127.0.0.1:8080 |
export default { fetch } con elide serve / elide dev |
127.0.0.1:8080 / 127.0.0.1:3000; --host y --port la cambian |
Elide. |
0.0.0.0 en port |
Rutas, JSON y streaming
URLPattern, Request.json(), Response.json() y los cuerpos ReadableStream son globales. Este servidor tiene una
API, una respuesta en streaming y archivos estáticos de public/:
// app.ts
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
const users = new URLPattern({ pathname: "/api/users/:id" });
const types: Record<string, string> = {
".html": "text/html; charset=utf-8",
".css": "text/css",
".js": "text/javascript",
};
async function api(request: Request): Promise<Response | null> {
const url = new URL(request.url);
const match = users.exec(url);
if (match && request.method === "GET") {
return Response.json({ id: match.pathname.groups.id });
}
if (url.pathname === "/api/users" && request.method === "POST") {
const body = await request.json();
return Response.json({ created: body.name }, { status: 201 });
}
if (url.pathname === "/api/ticks") {
let n = 0;
const stream = new ReadableStream({
async pull(controller) {
controller.enqueue(new TextEncoder().encode(`tick ${++n}\n`));
await new Promise((r) => setTimeout(r, 200));
if (n === 3) controller.close();
},
});
return new Response(stream, { headers: { "content-type": "text/plain" } });
}
return null;
}
async function file(pathname: string): Promise<Response> {
const path = join("public", normalize(pathname === "/" ? "/index.html" : pathname));
try {
const body = await readFile(path);
return new Response(body, { headers: { "content-type": types[extname(path)] ?? "application/octet-stream" } });
} catch {
return new Response("not found\n", { status: 404 });
}
}
export default {
port: Number(process.env.PORT ?? 3000),
async fetch(request: Request): Promise<Response> {
return (await api(request)) ?? file(new URL(request.url).pathname);
},
};
elide run app.ts
curl http://127.0.0.1:3000/api/users/42
curl -X POST -H 'content-type: application/json' -d '{"name":"ada"}' http://127.0.0.1:3000/api/users
curl -N http://127.0.0.1:3000/api/ticks
{"id":"42"}
{"created":"ada"}
tick 1
tick 2
tick 3
El POST responde 201 Created. Los tres ticks llegan con 200 ms de diferencia. / devuelve public/index.html, y un
archivo inexistente devuelve 404.
La misma API sobre node:http lee el cuerpo con node:stream/consumers y transmite con res.write:
// node-app.ts
import { createServer } from "node:http";
import { text } from "node:stream/consumers";
createServer(async (req, res) => {
if (req.method === "POST" && req.url === "/api/users") {
const body = JSON.parse(await text(req));
res.writeHead(201, { "content-type": "application/json" });
res.end(JSON.stringify({ created: body.name }));
return;
}
if (req.url === "/api/ticks") {
res.writeHead(200, { "content-type": "text/plain" });
for (let n = 1; n <= 3; n++) {
res.write(`tick ${n}\n`);
await new Promise((r) => setTimeout(r, 200));
}
res.end();
return;
}
res.writeHead(404).end();
}).listen(Number(process.env.PORT ?? 3000), "127.0.0.1");
Para servir solo archivos, use elide serve ./public; consulte Servidor de desarrollo.
Errores
Un manejador fetch que lanza una excepción o cuya promesa se rechaza responde 500 Internal Server Error y sigue
sirviendo. El error no se imprime, así que captúrelo y regístrelo usted mismo:
curl -i -d 'not json' http://127.0.0.1:3000/api/users
HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
content-length: 21
server: elide
date: Sat, 10 Oct 2026 00:34:28 GMT
Internal Server Error
TLS
Pase cadenas PEM como cert y key a Elide.serve, o como propiedades del objeto exportado. La clave debe ser PKCS#8
sin cifrar (BEGIN PRIVATE KEY). Los clientes que ofrecen HTTP/2 lo obtienen.
// tls.ts
import { readFileSync } from "node:fs";
Elide.serve({
port: Number(process.env.PORT ?? 8443),
cert: readFileSync("cert.pem", "utf8"),
key: readFileSync("key.pem", "utf8"),
fetch(request) {
return new Response("hello over tls\n");
},
});
elide run tls.ts
curl -i --cacert cert.pem https://localhost:8443/
HTTP/2 200
content-type: text/plain;charset=UTF-8
content-length: 15
server: elide
date: Sat, 10 Oct 2026 00:18:52 GMT
hello over tls
elide serve y elide dev no tienen opciones de TLS, y elide.pkl no tiene ajustes de TLS. https.createServer
lanza:
Error: HTTPS server is not supported in this runtime (no host TLS listener); use http.createServer behind a TLS terminator, or https client APIs.
Varios contextos
--contexts=N ejecuta N copias de una app con manejador fetch en un mismo puerto, en Linux. Cada copia tiene su
propio estado de módulo:
// counter.ts
let count = 0;
export default {
fetch(): Response {
count += 1;
return new Response(`${count}\n`);
},
};
elide serve --no-tui --contexts=4 counter.ts
for i in 1 2 3 4 5 6 7 8; do curl -s http://127.0.0.1:8080/; done
1
1
2
2
3
4
1
2
Guarde el estado compartido en una base de datos o en otro servicio. --contexts=auto ajusta el número a los núcleos
de CPU; engine.contexts en elide.pkl lo fija por proyecto
(Contextos del motor).
Ejemplo de Hono
En un directorio vacío, guarde esto como package.json:
{
"type": "module",
"dependencies": {
"hono": "4.13.16"
}
}
Instale la dependencia y después guarde el servidor siguiente como hono-app.ts:
elide install --ecosystems=npm
Para las dependencias de package.json, incluya --ecosystems=npm. Si no se puede importar Hono, consulte
Módulo no encontrado tras elide install.
// hono-app.ts
import { Hono } from "hono";
const app = new Hono();
app.get("/users/:id", (c) => c.json({ id: c.req.param("id") }));
app.post("/users", async (c) => c.json({ created: (await c.req.json()).name }, 201));
export default {
port: Number(process.env.PORT ?? 3000),
fetch: app.fetch,
};
Inicie el servidor:
elide run hono-app.ts
Desde una segunda terminal, compruebe las dos rutas:
curl http://127.0.0.1:3000/users/42
curl -X POST -H 'content-type: application/json' -d '{"name":"ada"}' http://127.0.0.1:3000/users
{"id":"42"}
{"created":"ada"}
El POST devuelve 201 Created. Detenga el servidor con Ctrl+C. Si una petición devuelve 500, consulte
Una petición devuelve 500 sin mostrar ningún error.
Ejemplos
- Manejador HTTP
- Rutas con URLPattern
- Servidor local y fetch
- Eventos enviados por el servidor
- Límites de peticiones
- Servidor con varios contextos