If we want to access a secure route and we’re redirected to the login route, then the login route should have the path to which we are redirected from so that we’re redirected to that particular path after logging in and not to the homepage. For this, in the +layout.server.ts
file of the (protected)
folder, we need to modify the load
function as follows —
To handle the redirect after logging in, we need to modify the action
function in login/+page.server.ts
as follows —
However, securing routes using +layouts.server.ts
will be tedious if we have large number of layouts. In every case we need to call await parent()
. To mitigate this, the above written code can be modified to —
The file for ./src/(auth)/login/+page.server.ts
can be removed.
We can then handle the redirects in the ./src/hooks.server.ts
file as —
Reference taken from tutorials by Huntabyte and some Google searches 😉