Sentry

Route protection and role-based access control.

Installation

npm install @kavach/sentry

Recommended Usage

When using Kavach, the sentry is managed automatically via kavach.handle:

// Simpler: use kavach.handle directly (recommended)
import { kavach } from '$kavach/auth'

export const handle = kavach.handle

Route rules are defined in kavach.config.js and applied automatically.

Standalone Setup

You can also use the sentry independently:

import { createSentry } from '@kavach/sentry'

const sentry = createSentry({
  rules: [
    { path: '/', public: true },
    { path: '/auth', public: true },
    { path: '/dashboard', protected: true },
    { path: '/admin', roles: ['admin'] },
    { path: '/moderator', roles: ['moderator', 'admin'] }
  ],
  roleHome: {
    admin: '/admin',
    user: '/dashboard'
  },
  routes: {
    login: '/auth',
    unauthorized: '/unauthorized'
  }
})

Protect Routes

// In your hooks.server.js
export const handle = async ({ event, resolve }) => {
  // Set session from cookie
  sentry.setSession(event.locals.session)

  // Protect route
  const protection = sentry.protect(event.url.pathname)

  if (protection.redirect) {
    return new Response(null, {
      status: 302,
      headers: { Location: protection.redirect }
    })
  }

  if (protection.status === 401 || protection.status === 403) {
    return new Response(null, {
      status: protection.status
    })
  }

  return resolve(event)
}

Rule Types

RuleDescription
{ path: "/", public: true }Public route
{ path: "/dashboard", protected: true }Any authenticated user
{ path: "/admin", roles: ["admin"] }Specific role(s)

API

createSentry(options)

Create a Sentry instance with rules.

sentry.setSession(session)

Set current session for protection checks.

sentry.protect(path)

Check if path is accessible. Returns { status, redirect? }.

Next Steps

Kavach — Authentication made simple llms.txt