App
To create a web server with ovr, initialize a new App
instance:
import { App } from "ovr";
const app = new App();
The App
API is inspired by and works similar to frameworks such as Hono and Express.
Configuration
The following values can be customized after creating the App
. You can also configure most of these per route within middleware by modifying the value on the Context
.
Trailing Slash
ovr handles trailing slash redirects automatically, you can customize the redirect preference.
app.trailingSlash = "never";
Not Found
Customize the not found response handler.
app.notFound = (c) => c.html("Not found", 404);
Error Handler
Add an error handler, by default errors are thrown.
app.error = (c, error) => {
console.error(error);
c.html("An error occurred", 500);
};
Base HTML
Change the base HTML to inject elements into with the Context.head
and Context.page
methods, this is the default.
app.base =
'<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
Response
At the most basic level, you can create a route and return a Response
from the middleware to handle a request.
app.get("/", () => new Response("Hello world"));
You can also return a ReadableStream
to use as the Response.body
.
JSX
Returning JSX from middleware will generate an HTML streamed response.
app.get("/", () => <h1>Hello world</h1>);
The element will be injected into the <body>
element of the base
HTML.
HTTP methods
app.get
and app.post
create handlers for the HTTP methods respectively. You can add other or custom methods with app.on
.
// Other or custom methods
app.on("METHOD", "/pattern", () => {
// ...
});
Multiple patterns
Add the same middleware to multiple patterns.
app.get(["/multi/:param", "/pattern/:another"], (c) => {
c.params; // { param: string } | { another: string }
});
Middleware
When multiple middleware handlers are added to a route, the first middleware will be called, and the next
middleware can be dispatched within the first by using await next()
. Middleware is based on koa-compose.
app.get(
"/multi",
async (c, next) => {
console.log("1");
await next(); // dispatches the next middleware below
console.log("3");
},
(c) => {
console.log("2");
},
);
The same Context
is passed into each middleware. After all the middleware have been run, the Context
will build
and return the final Response
.
Global Middleware
Add global middleware that runs in front of every request with app.use
.
app.use(async (c, next) => {
// ...
await next();
// ...
});
Fetch
Use the fetch
method to create a Response
, this is the Request
handler for your application.
const response = await app.fetch(new Request("https://example.com/"));