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`;
}
}
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.
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.
context
has a redirect function. Nuxt Docs
async asyncData(context) {
if (!context.authenticated) {
context.redirect(`${config.url}/sign_in`);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With