Guide
Server plugins
Plugins allow creating reusable interceptors to modify server options and behavior.
Example
This is a simple logging plugin:
import type { ServerPlugin } from "srvx";
export const logger: ServerPlugin = (server) => {
console.log(`Logger plugin enabled for ${server.runtime}`);
return {
name: "logger",
request: (req) => {
console.log(`[request] [${req.method}] ${req.url}`);
},
response: (req, res) => {
console.log(
`[response] [${req.method}] ${req.url} ${res.status} ${res.statusText}`,
);
},
};
};
We can use it in main server using plugins
option:
import { serve } from "srvx";
import { logger } from "./plugins/logger";
const server = serve({
plugins: [logger],
fetch(request) {
return new Response(`👋 Hello there.`);
},
});
await server.ready();
Defining plugins
import type { ServerPlugin } from "srvx";
const myPlugin: ServerPlugin = async (server) => {
// You can use server argument to:
// - Modify global options using server.options
// - Access to the runtime-specific server instance
// - Decide hooks based on server.runtime value
// Return plugin instance
return {
// Plugin display name
name: "my-plugin",
// Intercept incoming request
// You can return a Response value to early return (eg: auth and validation)
request: (request) => {},
// Intercept final response
// You can use to modify response
response: (request, response) => {},
};
};