ofj3kso
ofj3kso
SSolidJS
Created by ofj3kso on 3/3/2025 in #support
Auth guard
Hey there. I was trying to find a good solution to handle authentication and set up a guard that will redirect users to the authentication page if they are not authenticated. While reading this discussion (https://github.com/solidjs/solid-router/discussions/364), I couldn't help but notice this comment "This has the 2nd most upvotes of all time with no response" I didn't like so much the solutions, I want to propose mine and get @ryansolid comment on it, as I feel like this is an area with room for improvement, but I'm aware my solution might have blind spots or limitations I haven't considered
import {
Router,
Route,
redirect,
RoutePreloadFuncArgs,
} from "@solidjs/router"

const checkAuth = query(async function (
args: RoutePreloadFuncArgs,
auth: boolean
) {
"use server"

// COULD ALSO GET USER STATUS HERE

if (auth && args.location.pathname === "/auth") {
throw redirect("/")
}

if (!auth && args.location.pathname !== "/auth") {
throw redirect("/auth")
}
},
"checkAuth")

const App: Component = () => {
return (
<Router>
<Route
preload={args => createAsync(() => checkAuth(args, true))}
>
<Route path="/" component={Home} />
<Route path="/auth" component={Auth} />
{/* All other routes */}
</Route>
</Router>
)
}
import {
Router,
Route,
redirect,
RoutePreloadFuncArgs,
} from "@solidjs/router"

const checkAuth = query(async function (
args: RoutePreloadFuncArgs,
auth: boolean
) {
"use server"

// COULD ALSO GET USER STATUS HERE

if (auth && args.location.pathname === "/auth") {
throw redirect("/")
}

if (!auth && args.location.pathname !== "/auth") {
throw redirect("/auth")
}
},
"checkAuth")

const App: Component = () => {
return (
<Router>
<Route
preload={args => createAsync(() => checkAuth(args, true))}
>
<Route path="/" component={Home} />
<Route path="/auth" component={Auth} />
{/* All other routes */}
</Route>
</Router>
)
}
--- Optional: Lazy Loading Components
// Same checkAuth function either with or without "query"

const App: Component = () => {
return (
...
<Route path="/" component={lazy(() => import('./Home'))} />
<Route path="/auth" component={lazy(() => import('./Auth'))} />
{/* All other routes */}
...
)
}
// Same checkAuth function either with or without "query"

const App: Component = () => {
return (
...
<Route path="/" component={lazy(() => import('./Home'))} />
<Route path="/auth" component={lazy(() => import('./Auth'))} />
{/* All other routes */}
...
)
}
Benefits if you choose to use lazy loading: - Reduces initial bundle size - Improves initial load time
8 replies