PailFramework MiddlewareSvelteKit

SvelteKit

Request-scoped wide event logging hooks for SvelteKit

Last updated:

SvelteKit Hooks

The SvelteKit adapter provides handle and handleError hooks that attach a request-scoped Wide Event to every request. The event auto-emits when the response is sent or an error occurs.

Setup

// src/hooks.server.ts
import { createPail } from "@visulima/pail";
import { createPailHooks } from "@visulima/pail/middleware/sveltekit";

const logger = createPail();
const { handle, handleError } = createPailHooks({ pail: logger });

export { handle, handleError };

Using individual hooks

// src/hooks.server.ts
import { createPail } from "@visulima/pail";
import { pailHandle, pailHandleError } from "@visulima/pail/middleware/sveltekit";

const logger = createPail();

export const handle = pailHandle({ pail: logger });
export const handleError = pailHandleError();

Accessing the Logger

Via event.locals.log

In server load functions, actions, and API routes:

// src/routes/api/users/+server.ts
import type { RequestHandler } from "./$types";

export const GET: RequestHandler = async ({ locals }) => {
    locals.log.set({ user: { id: 1 } });
    locals.log.info("Fetched user list");
    return new Response(JSON.stringify({ ok: true }));
};
// src/routes/+page.server.ts
import type { PageServerLoad } from "./$types";

export const load: PageServerLoad = async ({ locals }) => {
    locals.log.set({ page: "home" });
    return { title: "Home" };
};

Via useLogger()

Access the logger from anywhere in the async call stack:

import { useLogger } from "@visulima/pail/middleware/sveltekit";

async function fetchUser(id: number) {
    const log = useLogger();
    log.set({ user: { id } });
    log.info("Querying database");
    // ...
}

How It Works

pailHandle

  1. Creates a WideEvent with the request method, pathname, headers, and request ID
  2. Attaches the logger to event.locals.log
  3. Enters AsyncLocalStorage context via storage.run()
  4. Calls resolve(event) to handle the request
  5. On success: emits with response.status
  6. On error: emits with the error, then re-throws

pailHandleError

Records errors to the wide event logger if one exists on event.locals.log. This ensures errors caught by SvelteKit's error boundary are included in the wide event.

Route Configuration

const { handle, handleError } = createPailHooks({
    pail: logger,
    service: "web-app",
    exclude: ["/health", "/_app/**"],
    include: ["/api/**", "/dashboard/**"],
    routes: {
        "/api/auth/**": { service: "auth-service" },
    },
});

TypeScript

For typed event.locals.log, augment SvelteKit's App.Locals:

// src/app.d.ts
import type { WideEvent } from "@visulima/pail/middleware/sveltekit";

declare global {
    namespace App {
        interface Locals {
            log: WideEvent;
        }
    }
}

Use the exported types for custom hook compositions:

import type { PailSvelteKitEvent, PailSvelteKitHandle } from "@visulima/pail/middleware/sveltekit";

Exported Types

ExportDescription
pailHandleCreate a SvelteKit handle hook
pailHandleErrorCreate a SvelteKit handleError hook
createPailHooksCreate both hooks at once
useLoggerRetrieve logger from AsyncLocalStorage
PailSvelteKitEventSvelteKit event with locals.log
PailSvelteKitHandleHandle hook function type
PailSvelteKitHandleErrorHandleError hook function type
PailSvelteKitHandleInputInput for the handle hook
PailSvelteKitHandleErrorInputInput for the handleError hook
PailSvelteKitResolveSvelteKit resolve function type
SvelteKitHandleOptionsOptions type for pailHandle()
WideEventRe-exported WideEvent class
Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues