Getting started
Welcome to Yggdrasil Server! Yggdrasil Server is a modern JavaScript library for managing context, errors, and routing when handling and responding to HTTP requests.
Quickstart
Step 1: Install Yggdrasil Server
- npm
- Yarn
- pnpm
npm install @jottocraft/yggdrasil --save
yarn add @jottocraft/yggdrasil
pnpm add @jottocraft/yggdrasil
Step 2: Construct a YggdrasilServer instance
src/server.ts
import { YggdrasilServer } from "@jottocraft/yggdrasil";
export type AppType = {
// The ctx object defines any arbitrary custom data
// to pass to your request handlers.
// Examples include environment variables, database bindings, etc.
ctx: {
env: DemoEnv;
ctx: ExecutionContext;
};
};
export const DemoServer = new YggdrasilServer<AppType>();
Step 3: Handle requests
src/index.ts
import { DemoServer } from "./server";
export default {
async fetch(request: Request, env: DemoEnv, ctx: ExecutionContext) {
return DemoServer.handleRequest(request, async (ygg) => {
// Yggdrasil Server uses YggdrasilStatus objects to indicate errors
// that you can either catch yourself, or ignore to let Yggdrasil Server
// generate an error page for you.
if (ygg.pathname !== "/") throw ygg.status(404, "INVALID_PATHNAME");
// You can do whatever you want to handle the request here.
return new Response("Hello World!", {
status: 200
});
},
{
// Your custom request context, available as ygg.ctx in request handlers.
ctx: {
env, ctx
}
},
// Yggdrasil Server options. These are specified here rather than in
// the YggdrasilServer object to support multi-tenancy.
{
debug: true
});
}
};
Explore more features
The quickstart example shows how to get up and running with the basic functionality of Yggdrasil Server. To continue exploring more powerful features, head to the "Features" section in the sidebar.