Preventing a user from directly accessing a route in ember.js

André Joaquim
Oct 16 · 2 min read
Photo by chris panas on Unsplash

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 🎉

Trouva Product Blog

Perspectives and updates from Trouva’s product team

André Joaquim

Written by

Product Engineer at Trouva and an Ember.js enthusiast

Trouva Product Blog

Perspectives and updates from Trouva’s product team

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade