Backend middleware library for SvelteKit.
-
Install (
npm i sveltekit-middleware
) -
Update your
src/app.d.ts
: (Read more)
declare global {
namespace App {
// interface Error {}
interface Locals {
_headers: Record<string, string>;
// Other locals
}
// interface PageData {}
// interface Platform {}
}
}
export {};
- Update
src/hooks.server.ts
, example:
import { useMiddleware } from "sveltekit-middleware"
import type { Handle } from "@sveltejs/kit"
export const handle: Handle = useMiddleware([
// If you don't use any middleware, the server will respond from the file system (`src/routes`)
// Put middleware here
])
Middleware is just a plain JavaScript function. If you return a valid response, the server will send that, otherwise it will go to the next function. It can pass on data with the locals
variable. locals._headers
will be appended to the response headers.
Example:
import { useMiddleware } from "sveltekit-middleware"
import { text, type Handle } from "@sveltejs/kit"
export const handle: Handle = useMiddleware([
// CORS
({ locals }) => locals._headers["Access-Control-Allow-Origin"] = "*",
() => text("Hello world!")
])
Use the match
function if you want to run some middleware on specific requests. Use the respondFromFileSystem
function to render the response from the Svelte files in the src/routes
folder.
import { useMiddleware, match, respondFromFileSystem } from "$lib"
import { text, type Handle, error } from "@sveltejs/kit"
export const handle: Handle = useMiddleware([
match("/api", "POST", () => text("Hello world")),
match("/", "GET", () => respondFromFileSystem()),
() => error(404, "Not Found"),
])