router5
  • Read Me
  • Introduction
    • Why router5?
    • Getting Started
    • Ecosystem
    • Core concepts
    • Transition phase
  • Guides
    • Defining routes
    • Path Syntax
    • Router options
    • Navigating
    • In the browser
    • Observing state
  • Integration
    • With React
    • With Redux
  • Advanced
    • Plugins
    • Middleware
    • Preventing navigation
    • Errors and redirections
    • Dependency injection
    • Loading async data
    • Universal routing
    • Listeners plugin
  • API Reference
  • Migration
    • Migrating from 7.x to 8.x
    • Migrating from 6.x to 7.x
    • Migrating from 5.x to 6.x
    • Migrating from 4.x to 5.x
    • Migrating from 3.x to 4.x
    • Migrating from 2.x to 3.x
    • Migrating from 1.x to 2.x
    • Migrating from 0.x to 1.x
Powered by GitBook
On this page
  • Using lifecycle functions
  • Using middleware functions
  1. Advanced

Preventing navigation

PreviousMiddlewareNextErrors and redirections

Last updated 6 years ago

It is a common case to want to allow / prevent navigation away from a view or component: if a User is in the middle of completing a form and data has not been saved, you might want to warn them about data being lost or prevent them to leave the current view until data has been saved.

Using lifecycle functions

Router5 supports canActivate and canDeactivate functions for route segments:

  • canActivate functions are called on segments which will become active as a result of a route change

  • canDeactivate functions are called on segments which will become inactive as a result of a route change

Both functions have the same signature than middleware functions. Their result can be synchronous (returning a boolean) or asynchronous (returning a promise or calling done(err, result)).

if a canActivate or canDeactivate function doesn't return a boolean, a promise or doesn't call back, the transition will not proceed.

const canActivate = (router) => (toState, fromState) => {
    return true;
}

router.canActivate('admin', canActivate);

canActivate functions are called from top to bottom on newly activated segments. canDeactivate methods are invoked from bottom to top.

Using middleware functions

Middleware functions behave like canActivate and canDeactivate. Read more about .

middleware