Preventing a user from directly accessing a route in Ember.js
At Trouva (we’re hiring!) we’re always aiming to improve our retailers’ experience by providing them with features to help them build their business around the world. Ember.js is the technology that powers up our retailer’s platform.
While building a new feature for retailers, we encountered the following problem:
We must prevent users from directly accessing the new
welcome
route, but we want to be able to send them ourselves to that route.
Using ember.js, we can very simply solve this problem.
We want to ensure this behaviour is triggered before the model
is loaded, so we’ll implement the logic in the beforeModel
hook. ember.js uses a routing microlib called router.js
, which implements the Transition
class. The beforeModel
hook receives the current Transition
as its sole argument.
Every Transition
has a sequence
property. This property tells in which order was this Transition
executed. If this is the initial transition, its value is 0
.
The snippet above implements the solution for our problem, by checking if the transition.sequence
is equal to 0
. In that case, it redirects the user to the index
page.
It’s worth noting that in this case it’s preferable to use replaceWith
instead of transitionTo
due to the fact that replaceWith
replaces the current history entry instead of adding a new one.
I hope you liked this small article on how to prevent a user from directly accessing a route in ember.js 🎉