Middleware on specific page - NuxtJS

Viewed 3060

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 Cookie.

Then i created a middleware

/middleware/auth.js

import Cookie from 'js-cookie'

export default function({ req, redirect }) {
  if (process.server) {
    if (!req.headers.cookie) return redirect('/login')
    const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('jwt='))
    if (!jwtCookie) return redirect('/login')
  } else {
    const jwt = Cookie.get('jwt')
    if (!jwt) { window.location = '/login' }
  }
}

and register the middleware in my layout or dashboard page

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

when I access /dashboard apparently works perfectly

but the problem is that the middleware is being registered globally, it is running on all pages, all routes

So when you access /home that is a published page, if you do not have the cookie, you end up being redirected to login page

anyone help?

3 Answers

How about creating a condition based on the route.path param ?

export default function({ req, redirect, route }) {

  if (!route.path.includes('dashboard')) { // if path doesn't include "dashboard", stop there
    return;
  }

  if (process.server) {
    if (!req.headers.cookie) return redirect('/login')
    const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('jwt='))
    if (!jwtCookie) return redirect('/login')
  } else {
    const jwt = Cookie.get('jwt')
    if (!jwt) { window.location = '/login' }
  }
}

Therefore you still benefit from the pre-render middleware system.

You probably have registered your middleware/auth.js in your nuxt.config.js. When you register a middleware in nuxt.config.js, you're registering it globally, meaning it will be called for every route change.

Docs: https://nuxtjs.org/guide/routing#middleware

In my opinion, you should call them plugin, because of middleware called by each route changed also you can't use middleware in layout and subComponent, you can use it as plugin and call it manually everywhere also it's reactive and runtime.

 path: /plugind/auth.js

 import Cookie from 'js-cookie';

 export default function({ req, redirect }) {
 if (process.server) {
   if (!req.headers.cookie) return redirect('/login')
    const jwtCookie = req.headers.cookie.split(';').find(c => 
    c.trim().startsWith('jwt='))
    if (!jwtCookie) return redirect('/login')
    } else {
    const jwt = Cookie.get('jwt')
   if (!jwt) { window.location = '/login'
   }
  }
 }
Related