Ember provides several hooks which can be used to redirect user to a different page what they request for.For example if a user is not logged in, you might want to prevent it from accessing the resources. Usually you want to redirect them to the login page and after they are successfully logged in, return them back to the page they wanted to access.

Ember allows you to control that access with a combination of hooks and methods in your route. In this blog, we are going to discuss the use of beforeModel(), afterModel() and redirect() route hooks.

beforeModel(): executes before the model hook.It is used to do a redirect if you don’t need any information from the model.It receives current transition as an argument which we can store and retry later.

In the above code the transitionTo() method is used to redirect to route “/posts” before the model is loaded.

afterModel(): executes after the model is resolved.It receives model as first argument and transition as the second one.

In the above code, when transitioning to route “/posts” if it has only one post object in the model, the current transition will be aborted  and redirected to route “/post/1”.

Problem with afterModel() hook : In case of a child route, if we redirect to child route from afterModel(), it invalidates the current attempt to enter this route. So the parent route’s beforeModel() and afterModel() will fire again with the new redirected transition.

redirect(): the above problem is solved by using the redirect hook as it leaves the original transition validated and not cause the parent route hooks to fire again.Lets see an example

In the above code, when transitioning to route “/posts”, if model has only one post object, it will be redirected to          “/posts/post/1”. The parent route’s beforeModel() and afterModel() hooks will not fire again as in the case of afterModel() hook.