Skip to content

Conversation

@fiorelorenzo
Copy link

The Route component now has 2 additional props:

  • canActivate: a boolean or a function returning a boolean (or a Promise) which tells the Router if the Route can be rendered. Useful for restricting access to a Route (e.g. a page that requires authentication)

  • canDeactivate: a boolean or a function returning a boolean (or a Promise) which tells the Router if it can navigate to another Route. Useful for restricting navigation out of a Route (e.g. when you have unsaved changes in a form)

Example:

<script>
  import { Router, Route } from "svelte-routing";
  import NavLink from "./components/NavLink.svelte";
  import Home from "./routes/Home.svelte";
  import About from "./routes/About.svelte";
  import Blog from "./routes/Blog.svelte";
  import Account from "./routes/Account.svelte";

  // Used for SSR. A falsy value is ignored by the Router.
  export let url = "";

  async function isLoggedIn() {
    // ...
  }
</script>

<Router url="{url}">
  <nav>
    <NavLink to="/">Home</NavLink>
    <NavLink to="about">About</NavLink>
    <NavLink to="blog">Blog</NavLink>
  </nav>
  <div>
    <Route path="about" component="{About}" />
    <Route path="blog/*" component="{Blog}" />
    <!-- if isLoggedIn() returns a truthy (or a Promise that resolves to a truthy), the component will be rendered -->
    <Route path="account" component="{Account}" canActivate={isLoggedIn} />
    <Route path="/" component="{Home}" />
  </div>
</Router>

If you use the slot in the Route, shouldActivate & shouldDeactivate (booleans) will be passed back:

<Router {url}>
  <Route path="account" canActivate={isLoggedIn} let:shouldActivate>
    {#if shouldActivate}
      <Account />
    {:else}
      <!-- redirect to login  -->
    {/if}
  </Route>
</Router>

The Link component won't navigate to a Route if its canActivate is or returns a falsy.
Just as it won't navigate out of a Route if its canDeactivate is or returns a falsy.

If you skip the Link and navigate directly to a location with a falsy canActivate the Route's component won't be rendered.

@Spaceman2019
Copy link

Spaceman2019 commented Aug 16, 2023

The pull request is now open since three years. When it will be merged? I'm looking for this functions.

@tgf9
Copy link

tgf9 commented Mar 2, 2024

Also looking for this functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants