@sveltecult/router-core v0.0.3
Sveltekit Fluent Router
Sveltekit Fluent Router is an experimental library that offers per-route authorization, multiple middlewares, and a customizable optional handler, all with an expressive syntax. Please note that this library is currently in an 🚨 experimental 🚨 stage and may undergo changes.
Why
- Middleware and Authorization Reusability: Simplify the reuse of middlewares and authorization settings such as "authenticated," "verified," or "pro" users.
- Centralized Source of Truth: Provides a single source of truth for defining middleware and authorization rules, moving away from manual edits in every
+page.server.ts
files.
Installation
To install this package, use your preferred package manager:
npm install @sveltecult/router-core
Basic Usage
To add authorization and middleware for a single route, you can do this:
import { Router, RouterGroup } from '@sveltecult/router-core';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
Router.add()
.authorize(true)
.middleware([])
.uri('/', () => {});
return Router.build(event, resolve);
}
or with grouped routes:
Router.add()
.prefix('admin') // this will prefix all URI under this group
.authorize(false) // authorization will be applied to all routes under this group
.middleware([]) // middleware will be applied to all routes under this group
.group((RouterGroup: RouterGroup) => {
RouterGroup.uri('/'); // this will match "/admin/" URI
RouterGroup.authorize(true).uri('/posts'); // this will override the global authorize() and will match "/admin/posts"
});
Please note that you can override group's authorize()
and middleware()
inside your RouterGroup
.
Available Functions
.add()
: Initializes the router instance for method chaining..authorize(authorized: boolean | Authorize)
: Accepts a boolean or an asynchronous function that returns a boolean for authorization..middleware(middleware: Middleware | Middleware[])
: Accepts a function or an array of functions that return a response or void..prefix(prefix: string)
: Adds a prefix to the URI, useful for grouped routes..uri(uri: string, handler?: Handler)
: Adds a single route with an optional custom handler..group(callback: (RouterGroup) => void)
: Useful for grouping similar routes that share the same authorization, middleware, etc..build(event: RequestEvent, resolve: Function)
: Builds all the routes, applies authorization, middleware, and any custom handler if defined.
Disclaimer
Please be aware that this library is experimental and might not be suitable for production use. Use it at your own discretion.
Contributing
Contributions are welcomed! Feel free to open issues or submit pull requests.
License
This project is licensed under the MIT License.