Access LocalStorage in Middleware – NuxtJs

Tags: , , , ,



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.

Answer

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')
    }
}


Source: stackoverflow