Search code examples
nuxt.jsnuxt-auth

NuxtJS route middleware for specific routes


I want to protect certain routes to be only available when a user is logged in. The way I want to do this is make a API call to verify the current token.

The token can be either in Local storage or the store (VueX).

I created a middleware called auth.js in the middleware folder and added it to the nuxt.config.js file.

export default function ({ store, redirect }) {
  if (!process.client && !store.getters['user/getUserToken']) {
    return redirect('/login')
  }
}

The problem I have now is that process.client is ignored and this code is fired on the server (SSR) and thus results in an error "localStorage is not defined".

I have been trying to get this working for three days now, so hopefully someone can explain to me how to get this working.

What I want to achieve is that I am able to make a API request BEFORE the page is loaded to verify the user his token. The token can be stored in either the VueX store or localstorage. So I need to have access to both.

Hope someone can help me out on how to get this working.

FYI I am using the fetch method and not Axios or something like that. Using Axios is, for this project, not an option because we would need to refactor to much.


Solution

  • If you're not using nuxt/auth but a homemade solution, you can still get inspired by my answer here: https://stackoverflow.com/a/68175140/8816585

    My global.js middleware is complementary to the auth one (from nuxt/auth) but the logic can be done in the same way there too.

    Some takeaways:

    • a middleware is always run before your page is rendered, hence you are not obliged to do this on the server, the verification will still happen before the content is visible
    • prefer using a cookie rather than localStorage, more secure and available on both server and client
    • using either axios or fetch is not a big deal IMO because they basically do the exact same thing (overall)
    • axios can be renamed into fetch, especially if you have a generic configurable file, a bit hacky but requires less maintenance IMO