Sering kali kita memerlukan halaman yang diproteksi. Hanya user yang sudah login yang bisa masuk ke halaman tersebut.
Buat Halaman src/routes/AccessDenied.svelte
<script>
import { Link } from "svelte-routing"
import { PATH_URL } from "../helper/path"
</script>
<h1>No access 🤕</h1>
<h2>
Go back to <Link to={PATH_URL.BASE}>Home page</Link>
</h2>
<script> import { Route } from "svelte-routing" import AccessDenied from "./routes/AccessDenied.svelte" import { token } from "./stores/token.js" export let path export let component $: isAuthenticated = $token;</script>{#if isAuthenticated} <Routepath={path} component={component} />{:else} <Routepath={path} component={AccessDenied} />{/if}
Buat file src/routes/UserList.svelte
<h1>List User</h1>
Ubah file src/App.svelte
<script> import { Router, Route } from "svelte-routing" import About from "./routes/About.svelte" import Home from "./routes/Home.svelte" import { PATH_URL } from "./helper/path" import UserList from "./routes/UserList.svelte" import ProtectedRoute from "./ProtectedRoute.svelte"</script><Router> <Routepath={PATH_URL.BASE} component={Home}/> <Routepath={PATH_URL.ABOUT} component={About}/> <ProtectedRoutepath={PATH_URL.USER_LIST} component={UserList} /></Router>