0.0.2 • Published 1 year ago

sveltekit-middleware v0.0.2

Weekly downloads
-
License
-
Repository
-
Last release
1 year ago

SvelteKit Middleware

Backend middleware library for SvelteKit.

How to use

  1. Install (npm i sveltekit-middleware)

  2. 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 {};
  1. 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"),
])
0.0.2

1 year ago

0.0.1

1 year ago