Is this a good way to handle auth in hooks.server.ts?

import { building } from '$app/environment';
import { auth } from '$lib/server/auth';
import { redirect, type Handle } from '@sveltejs/kit';
import { svelteKitHandler } from 'better-auth/svelte-kit';

export const handle: Handle = async ({ event, resolve }) => {
  const isProtectedRoute = event.route.id?.startsWith('/(protected)/');
  const isAuthRoute = event.route.id?.startsWith('/(auth)/');

  // Only check session for protected and auth routes
  if (isProtectedRoute || isAuthRoute) {
    const session = await auth.api.getSession({
      headers: event.request.headers
    });

    const hasSession = !!session;

    // Protected routes: require authentication
    if (isProtectedRoute && !hasSession) {
      throw redirect(307, '/sign-in');
    }

    // Auth routes: redirect if already authenticated
    if (isAuthRoute && hasSession) {
      throw redirect(307, '/dashboard');
    }

    // Set session data for authenticated users on protected routes
    if (isProtectedRoute && hasSession) {
      event.locals.session = session.session;
      event.locals.user = session.user;
    }
  }

  return svelteKitHandler({ event, resolve, auth, building });
};
Was this page helpful?