Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect after checking in Nuxt Asyncdata

I am running Nuxt and I have the below function. I want to check if authenticated then redirect to the login page if not. I am getting the error window is undefined This make since because it is my understanding that asyncdata() is evaluated server side. What is the correct way to redirect. I tried to use the redirect method in context but it just brings up my 404. Thanks

 async asyncData(context) {
    if (!context.authenticated) {
      window.location = `${config.url}/sign_in`;
    }
  }
like image 750
lukechambers91 Avatar asked Jul 30 '19 18:07

lukechambers91


People also ask

When to use asyncData vs fetch NUXT?

Unlike fetch , asyncData cannot access the component instance ( this ). Instead, it receives the context as its argument. You can use it to fetch some data and Nuxt will automatically shallow merge the returned object with the component data.

What is nuxtServerInit?

nuxtServerInit: it is used to fetch some data you work with a lot (such as userInfo in the session), only once, then you can use it in all the components. So, you don't have to constantly reach out to the server. Moreover, it is an action in the store provided by Vuex, so it'll dispatch automatically by Vuex.


1 Answers

context has a redirect function. Nuxt Docs

 async asyncData(context) {
    if (!context.authenticated) {
      context.redirect(`${config.url}/sign_in`);
    }
  }
like image 161
lukechambers91 Avatar answered Oct 17 '22 19:10

lukechambers91