0Pricing
Sveltejs Academy · Lesson

Protected Routes in handle() Hook

Redirect unauthenticated users from protected routes inside the handle hook.

Protect at the Edge

Centralize route protection in the handle hook for one source of truth.

Check Locals

If you set event.locals.user in handle, check it for protected paths.

export async function handle({ event, resolve }) {
  event.locals.user = await getUser(event);
  if (event.url.pathname.startsWith("/admin") && !event.locals.user) {
    return new Response("Unauthorized", { status: 302, headers: { Location: "/login" } });
  }
  return resolve(event);
}

All lessons in this course

  1. Cookie-Based Sessions
  2. JWT in HTTP-Only Cookies
  3. Protected Routes in handle() Hook
  4. OAuth with SvelteKit and Lucia Auth
← Back to Sveltejs Academy