npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

svelte-guard

v0.1.3

Published

`svelte-guard` is a lightweight and flexible package designed to make route guarding in SvelteKit applications easy and efficient. It ensures that only authorized users can access specific routes, enhancing your app’s security. With `svelte-guard`, you ca

Downloads

260

Readme

SvelteGuard: Route Guards for SvelteKit

svelte-guard is a lightweight and flexible package designed to make route guarding in SvelteKit applications easy and efficient. It ensures that only authorized users can access specific routes, enhancing your app’s security. With svelte-guard, you can manage route guards seamlessly, avoiding redundant code across your project.

Features

  • ✅ Simple Setup: Easily define route guards by adding individual guard files to your routes.
  • ✅ Flexible Guards: Supports both synchronous and asynchronous guard functions. Guards can redirect users to another route if access is denied.
  • ✅ Inherited Guards: Guards can be inherited from parent routes, minimizing duplication of guard logic.
  • ✅ Extensible: You can extend existing guards to add extra logic for specific routes or groups of routes.

Directory Structure Example

app/
│-- routes/
│   │-- login/
│   │   ├── -guard.ts          # Guard for login route
│   │   └── +page.svelte
│   │-- admin/
│   │   ├── settings/
│   │   │   ├── -guard.ts      # Extends admin guard
│   │   │   └── +page.svelte
│   │   ├── -guard.ts          # Admin guard for all sub-routes
│   │   └── +page.svelte
│   └── +layout.svelte
│-- hooks.server.ts            # Register guards here

Installation

Install svelte-guard via npm:

npm install svelte-guard

Getting Started

To use svelte-guard, you need to define guard files for your routes and register them.

1. Create Guard Files

Define guards in `-guard.ts` (or `.js`) files inside your route directories. Each guard file controls access to its associated route and its children.

Example:

// routes/admin/-guard.ts
import type { Guard } from 'svelte-guard';
import { redirect } from '@sveltejs/kit';

export const guard: Guard = async ({ locals }) => {
	// Example: Check if the user is an admin
	if (!locals.user.isAdmin) {
		return false; // Access denied
		// or redirect the request in here:
		// return redirect(307, '/');
	}
	return true;
};

// Optional redirect for unauthorized users
// this will be the default for nested sub-routes
export const reroute = '/';

2. Register Guards

In `hooks.server.ts`, register your route guards using the `createGuardHook` function from `svelte-guard`:

// hooks.server.ts
import { createGuardHook } from 'svelte-guard';

const guards = import.meta.glob('./routes/**/-guard.*');
export const handle = createGuardHook(guards);
// Optional: Specify a default redirect route if a guard fails
// export const handle = createGuardHook(guards, '/login');

Example Guards

Basic Route Guard

// src/routes/dashboard/-guard.ts
import type { Guard } from 'svelte-guard';

export const guard: Guard = async ({ locals }) => {
	return locals.session === undefined;
};

// Redirect if the guard fails
export const reroute = '/login';

API Endpoint Guard

// src/routes/api/-guard.ts
import type { Guard } from 'svelte-guard';

export const guard: Guard = async (event) => {
	const header = request.headers.get('Authorization');
	const token = 'xxxxxxxxxxxxxxxx';
	if (!header || header !== `Bearer ${token}`) {
		return false;
	}

	return true;
};

// No reroute specified = 403 Forbidden on failure

Advanced Configuration

You can chain multiple hooks together using SvelteKit’s `sequence` function:

// hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { createGuardHook } from 'svelte-guard';

const guards = import.meta.glob('./routes/**/-guard.*');
const GuardHook = createGuardHook(guards);

export const handle = sequence(OtherHook, GuardHook);

VSCode Settings

To help you easily identify guard files in VSCode, you can enable custom labels for tabs. Add the following to your `settings.json`:

"workbench.editor.customLabels.enabled": true,
"workbench.editor.customLabels.patterns": {
  "**/src/routes/**/-guard.{ts,js}": "${dirname} - Guard"
}

Contributing

We welcome contributions to `svelte-guard`! Whether it's fixing bugs, adding new features, or suggesting improvements, feel free to open issues or submit pull requests on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.