S
SolidJS6mo ago
be_cool

Best approach to having protected routes in SolidJs?

Hello, I'm working on securing certain routes in my application to ensure they are protected if a user is not logged in. There are about 10-15 pages that need to be restricted. I'm currently using Better-Auth for authentication and have switched to client-side rendering only for now.
9 Replies
be_cool
be_coolOP6mo ago
Also I am using an external API, and using axios to fetch data
peerreynders
peerreynders6mo ago
Typically you want to create a route layout which verifies authentication and redirects to /login when not authenticated while all the protected routes are nested within the “protected” layout.
zulu
zulu6mo ago
Auth - SolidDocs
Documentation for SolidJS, the signals-powered UI framework
zulu
zulu6mo ago
No description
zulu
zulu6mo ago
peerreynders
peerreynders6mo ago
Example:
|-- routes/
|-- (protected).tsx // layout checks auth
|-- (protected) // protected routes inside
|-- index.tsx // example.com (protected)
|-- user
|-- [id].tsx // example.com/user/{id} (prot)
|-- login.tsx // example.com/login (not)
|-- about
|-- index.tsx // example.com/about (not)
|-- routes/
|-- (protected).tsx // layout checks auth
|-- (protected) // protected routes inside
|-- index.tsx // example.com (protected)
|-- user
|-- [id].tsx // example.com/user/{id} (prot)
|-- login.tsx // example.com/login (not)
|-- about
|-- index.tsx // example.com/about (not)
- Route Groups - Nested Layouts - Nested Routes keywords: protected file system routes
odili
odili2mo ago
Hi @peerreynders , Thank you for this suggested approach of using Route group layout to manage protected pages. I have implemented as you recommended however I running into a small issue: I'm using Better-Auth, so the getSession() requires a context but essentially the Header passed as argument. See below:
getSession: <R extends boolean>(context: {
headers: Headers;
query?: {
disableCookieCache?: boolean;
disableRefresh?: boolean;
};
asResponse?: R;
}) => false extends R ? Promise<PrettifyDeep<Awaited<ReturnType<E>>>> & {
options: E["options"];
path: E["path"];
} : Promise<Response>;
getSession: <R extends boolean>(context: {
headers: Headers;
query?: {
disableCookieCache?: boolean;
disableRefresh?: boolean;
};
asResponse?: R;
}) => false extends R ? Promise<PrettifyDeep<Awaited<ReturnType<E>>>> & {
options: E["options"];
path: E["path"];
} : Promise<Response>;
So, which route API in SolidStart provides the required Headers? Currently, RoutePreloadFunc, RouteSectionProps and RouteDefinition doesn't.
Madaxen86
Madaxen862mo ago
getRequestEvent -
Documentation for SolidJS, the signals-powered UI framework
odili
odili2mo ago
Thank you, @Madaxen86 . Yea, it did it for me. I'm most grateful!

Did you find this page helpful?