sveltekit-middleware
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

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"),
])

Readme

Keywords

none

Package Sidebar

Install

npm i sveltekit-middleware

Weekly Downloads

5

Version

0.0.2

License

none

Unpacked Size

8.53 kB

Total Files

12

Last publish

Collaborators

  • digital-daniel