Fetch handler
Request handler is defined via fetch
key since it is similar to fetch API. The input is a Request object and handler should return a Response or a promise if the server handler is async.
Example:
import { serve } from "srvx";
serve({
async fetch(request) {
return new Response(
`
<h1>👋 Hello there</h1>
<p>You are visiting ${request.url} from ${request.ip}</p>
`,
{ headers: { "Content-Type": "text/html" } },
);
},
});
ServerRequest
type export from srvx
as type of request
.Extended request context
request.ip?
Using request.ip
allows to access connected client's IP address.
import { serve } from "srvx";
serve({
fetch: (request) => new Response(`Your ip address is "${request.ip}"`),
});
request.runtime?.name?
Runtime name. Can be "bun"
, "deno"
, "node"
, "cloudflare"
or any other string.
request.runtime?.bun?
Using request.bun?.server
you can access to the underlying Bun server.
request.runtime?.deno?
Using request.deno?.server
you can access to the underlying Deno server.
Using request.deno?.info
you can access to the extra request information provided by Deno.
request.runtime?.node?
Node.js is supported through a proxy that wraps node:IncomingMessage as Request and converting final state of node:ServerResponse to Response.
If access to the underlying Node.js request and response objects is required (only in Node.js runtime), you can access them via request.runtime?.node?.req
(node:IncomingMessage) and request.runtime?.node?.res
(node:ServerResponse).
import { serve } from "srvx";
serve({
fetch: (request) => {
if (request.node) {
console.log("Node.js req path:", request.node?.req.path);
req.node.res.statusCode = 418; // I'm a teapot!
}
return new Response("ok");
},
});