import { serve } from "https://deno.land/x/ayonli_jsext@v0.9.72/http.ts";
Serves HTTP requests with the given options.
This function provides a unified way to serve HTTP requests in all server
runtimes, even worker runtimes. It's similar to the Deno.serve
and
Bun.serve
functions, in fact, it calls them internally when running in the
corresponding runtime. When running in Node.js, it uses the built-in http
or http2
modules to create the server.
This function also provides easy ways to handle Server-sent Events and WebSockets inside the fetch handler without touching the underlying verbose APIs.
Currently, the following runtimes are supported:
- Node.js (v18.4.1 or above)
- Deno
- Bun
- Cloudflare Workers
- Fastly Compute
- Service Worker in the browser
NOTE: WebSocket is not supported in Fastly Compute and browser's Service Worker at the moment.
Examples
Example 1
Example 1
// simple http server
import { serve } from "@ayonli/jsext/http";
serve({
fetch(req) {
return new Response("Hello, World!");
},
});
Example 2
Example 2
// set the hostname and port
import { serve } from "@ayonli/jsext/http";
serve({
hostname: "localhost",
port: 8787, // same port as Wrangler dev
fetch(req) {
return new Response("Hello, World!");
},
});
Example 3
Example 3
// serve HTTPS/HTTP2 requests
import { readFileAsText } from "@ayonli/jsext/fs";
import { serve } from "@ayonli/jsext/http";
serve({
key: await readFileAsText("./cert.key"),
cert: await readFileAsText("./cert.pem"),
fetch(req) {
return new Response("Hello, World!");
},
});
Example 4
Example 4
// respond Server-sent Events
import { serve } from "@ayonli/jsext/http";
serve({
fetch(req, ctx) {
const { events, response } = ctx.createEventEndpoint();
let count = events.lastEventId ? Number(events.lastEventId) : 0;
setInterval(() => {
const lastEventId = String(++count);
events.dispatchEvent(new MessageEvent("ping", {
data: lastEventId,
lastEventId,
}));
}, 5_000);
return response;
},
});
Example 5
Example 5
// upgrade to WebSocket
import { serve } from "@ayonli/jsext/http";
serve({
fetch(req, ctx) {
const { socket, response } = ctx.upgradeWebSocket();
socket.addEventListener("message", (event) => {
console.log(event.data);
socket.send("Hello, Client!");
});
return response;
},
});
Example 6
Example 6
// module mode (for `deno serve`, Bun and Cloudflare Workers)
import { serve } from "@ayonli/jsext/http";
export default serve({
type: "module",
fetch(req) {
return new Response("Hello, World!");
},
});
Parameters
options: ServeOptions