Authenticated routes in SPA
I wanted to expose this question to more people and thought of this discord server.
Original post in GH:
https://github.com/solidjs/solid-router/discussions/364
The TL;DR; is that there doesn't seem to be a canonical approach to handling private vs public routes such that repetition is avoided -- I.E some type of middleware or guard.
I posted what I'm currently playing around with and will add it here for feedback, though in its current state it isn't working as expected. When using nested routes in the config-based approach this doesn't work.
GitHub
Is there a recommended way to implement Authenticated Routes? · sol...
Assume you have a SPA that includes several public Routes and several private Routes that require an authenticated user. Ideally, I'd like to wrap all of those protected Routes under a single c...
4 Replies
Place your guard from the server side instead, on the client side, you just need to care whether the user is in the right view
There are guards on the api for resource requests via
Authenticatiion
header / bearer token. I'm using a SPA, so the server doesn't receive a request for a new page on navigate, so checking for auth needs to happen at the FE router level and this can be a request to the auth service (or internal API if that is also the auth service) but it can't only happen on the server. I already have a way to refresh a token or redirect to login upon an Unauthenticated request for a resource.
I posted another solution in that GH link that I'll likely end up going with.
TL;DR;
Config-based routes seem like an after thought in @solidjs/router
, perhaps by design? 🤷🏼♂️ Using the JSX-based approach is significantly easier to handle a groupings of "private" routes. See my comment.This is a setup that I use. AuthGuard is a layout component which does not affect the url.
In getIsAuthenticated will refresh the session / token and returns a boolean respectively, hence the Switch + Match setup and also the refresh interval for the token refresh. Works like charm for me.
Stackblitz: https://stackblitz.com/edit/github-p2tzuc?file=src%2Froutes%2F(authLayout).tsx
StackBlitz
Solid-start Basic Example - StackBlitz
Run official live example code for Solid-start Basic, created by Solidjs on StackBlitz
This approach is good, but there's nothing unique to JSX routes with what you're doing
Config routes would also work and in fact using JSX routes is just a fancy way of building a config object