how to add auth protected route or layout in a better way?

// Auth Layout
import { useNavigate } from "@solidjs/router";
import type { ParentProps } from "solid-js";
import { useAuth } from "~/context/auth-context";

export default function DashboardLayout(props: ParentProps) {
    const auth = useAuth();
    const navigate = useNavigate();

    if (!auth.user()) {
        navigate("/login", { replace: true });
        return null;
    }

    return <>{props.children}</>;
}


// Main file
import { lazy } from "solid-js";
import { render } from "solid-js/web";
import { Router } from "@solidjs/router";

import { AuthProvider } from "./context/auth-context";

const wrapper = document.getElementById("root");

if (!wrapper) {
    throw new Error("Wrapper div not found");
}

const routes = [
    {
        path: "/dashboard",
        component: lazy(() => import("~/routes/dashboard/layout")), // Is it the correct way
        children: [
            {
                path: "",
                component: lazy(() => import("~/routes/dashboard/index")),
            },
        ],
    }
];

render(
    () => (
            <AuthProvider>
                <Router>{routes}</Router>
            </AuthProvider>
    ),
    wrapper,
);
Was this page helpful?