Search code examples
javascriptnuxt.jslocal-storagemiddleware

How to use middlewares one more time in Nuxt.js universal mode?


I have middleware that I need to check if user authenticated every time he visits page. For now it seems like this, just to make sure if it's able to work with localStorage:

export default function({ store, redirect, route }) {
  console.log('Here is auth middleware')
  console.log(localStorage.getItem('token'))
}
// nuxt.config.js
  plugins: [
    '~/plugins/test.client.js'
  ],

Generally, this middleware has to work with localStorage. Here I found solution of my problem, but it works only one time (from documentation):

In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes

So, I need to create such middleware, that is going to work only on specific pages and be able to work with localStorage with Nuxt.js app in universal mode. Is it possible to implement?


Solution

  • This problem can be solved using mixins. In mixins/auth.js I have this code:

    import { verifyToken } from "@/api";
    export default {
      async mounted() {
        if (!localStorage.getItem('token')) {
          await this.$router.push({path: '/login'})
        } else {
          const checkToken = await verifyToken({ token: localStorage.getItem('token') })
          if (checkToken.error) {
            localStorage.removeItem('token')
            await this.$router.push({path: '/login'})
          }
        }
      }
    }
    

    And then, on page where I need to check is there is valid token in localStorage I just do this:

    <script>
    import auth from '~/mixins/auth'
    export default {
      name: "Component",
      mixins: [auth],
    </script>