Hook to protect routes
See original GitHub issueDescribe the problem
I would like to propose the addition of a protect
function that can be used to redirect unauthenticated or unauthorized access to pages or endpoints.
Current State
- The
handle
is only executed during a fetch or a forced reload - The
load
function in__layout.svelte
is called only once for all routes using it - Adding
load
function purely for route protection is inefficient and error-prone - There is no
load
equivalent for endpoints and in some scenarios cannot be protected using the handle function
Describe the proposed solution
Proposal: Add a user-customizable protect
function that can be written in hooks
, where we can add our custom code for validating and identifying alternate fallback routes when the user is not allowed access.
- This function should be called prior to
handle
on fetch or forced reload of any URL - This function should be called prior to client-side navigation to any endpoint or route
- Since shadow endpoints are dependent on the page route, calling this function once prior to routing to the page
- This function should receive the session from getSession
// hooks.js
export async function protect({url, session}) {
// custom logic to identify allowed requests and rerout it
const {allowed, fallbackUrl} = isUserAllowed(url, session)
if (allowed) {
return { status: 200 }
} else {
return { status: 302, redirect: fallbackPath}
}
}
or
export async function protect({url, session}) {
// custom logic to identify aalternate URL when not authorized
const falbackUrl = getFallbackUrl(url, session)
return fallbackUrl || url.pathname
}
Alternatives considered
Writing the protect function in the handle and in multiple load functions.
Importance
it would make my life easier
Additional Information
Svelte-Kit really makes application development a breeze and I would really like to move our application development over to SvelteKit. Almost all our web applications require authentication and some form of route protection. This feature will make it a lot easier to incorporate authentication and role-based route protection.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:13
- Comments:22 (8 by maintainers)
Hi, This workflow is a bit complex to me. May I ask for a tiny example of the logic in the documentation?
Whatever method is arrived at, it would be very nice if types could be propagated, so that I might set-up a guard that checks that I have an authenticated user and sets
request.locals.user
and then in routes that are protected by that guardrequest.locals.user
is known not-null, and so on. I don’t have the first clue whether or how this would be possible.