Nuxt - can i run client side code from a middleware in Universal mode?

Jay*_*K23 5 javascript vue.js nuxt.js

I'm working on a universal Nuxt app that uses the standard Django session authentication. I need to restrict some pages in my project to logged in users only, so i decided to use a middleware.

The problem with the middleware is that it will run from server side, so it will always return False to the user even when the user is logged in, since it doesn't send any cookie in the request. This happens only when i refresh page or when i navigate directly to it, not when i navigate from another page to a restricted page, that's because in that case the middleware is executed client side and not server side.

Is there any way i can "force" the following code to run client side instead of server side from the middleware? Or do i have to look for another solution?

export default async function (context) {
  axios.defaults.withCredentials = true;
  return axios({
    method: 'get',
    url: 'http://127.0.0.1:8000/checkAuth',
    withCredentials: true,
  }).then(function (response) {
    //Check if user is authenticated - response is always False
  }).catch(function (error) {
    //Handle error
  });
}
Run Code Online (Sandbox Code Playgroud)

I tried to do the same with nuxtServerInit but the outcome is the same. If i run that code in the beforeCreate block from the page it will first load the page and then execute the request, which works but it's quite ugly since the user will see the page for a second before being redirected.

小智 6

还有另一种方法可以解决这个问题。首先,您只需在客户端运行中间件代码。

export default async function (context) {
   if(process.client) {
      // your middleware code here
   }
}
Run Code Online (Sandbox Code Playgroud)

现在您只需处理应用程序的首次加载即可。您可以创建一个仅在客户端运行的插件,并使用插件内的中间件代码。要仅在客户端上运行插件,请使用这样的模式关键字。这是 nuxt.config.js:

plugins: [ 
    { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side 
  ]
Run Code Online (Sandbox Code Playgroud)