0.0.2 • Published 3 years ago
sveltekit-middleware
Licence
—
Version
0.0.2
Deps
0
Size
8 kB
Vulns
0
Weekly
0
SvelteKit Middleware
Backend middleware library for SvelteKit.
How to use
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"),
])