Access LocalStorage in Middleware - NuxtJs

纵饮孤独 提交于 2020-01-04 05:46:20

问题


Well, I'm starting with nuxt and I have following routes:

/home

/dashboard

/login

I want to protect the /dashboard, but only for users logged in with a token in localStorage.

The simplest way I thought of doing this was by creating a /middleware/auth.js

export default function () {
  if (!window.localStorage.getItem('token')) {
    window.location = '/login'
  }
}

and registering it in the /dashboard/index.vue component.

<script>
export default {
  middleware: 'auth',
}
</script>

But I cannot access localStorage within a middleware, because LocalStorage is client-side.

I have already tried to add this same check in the created() dashboard layout, but I cannot return window not set mounted() is too late, it can only check after the page has been fully assembled.

So how can I achieve this? Note: I do not intend to use any Vuex for this project.


回答1:


I used cookie-universal-nuxt

on vuex store for login action i set a commit with the token

window.$nuxt.$cookies.set('token', payload, {
            path: '/',
})

middleware/auth.js

export default (context) => {
    if (!context.app.context.app.$cookies.get('token')) {
        return context.redirect('/login')
    }
}



回答2:


For anyone not satisfied storing the information in cookies, here's me solution:

I've been having a lot of problems with this and I were not satisfied setting a cookie. If you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as:

Isomorphic application (server-side rendering + client-side navigation)

The result being that localStorage is not defined serverside and thus throws an error.

The give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.

The solution for me was to change the mode to spa in the nuxt.config.js which is located at the root.

Please notice that you can still access localStorage, running universal mode, in page files and components because they are not server side.

Middleware files are, in universal mode, run server side, so changing to spa mode makes them run client side and thus allows them access to localStorage.

For more information about Nuxt modes, read these:

  • https://nuxtjs.org/guide/
  • https://recurse.me/posts/choosing-a-nuxt-mode.html



回答3:


You could use something like this for storage in nuxt, that will work both client and server side

https://github.com/alibaba-aero/nuxt-universal-storage



来源:https://stackoverflow.com/questions/52240262/access-localstorage-in-middleware-nuxtjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!