GithubHelp home page GithubHelp logo

Comments (22)

jd1378 avatar jd1378 commented on August 16, 2024 1

Can't you just use process.server or process.client for detecting the environment and get the cookie ?
Edit: Ah sorry, I wasn't taking into mind that this is nuxt specific and does not work in other environments (And cookie universal is not nuxt only)
In any case , I Can't think of a way it be happening, thanks again for explaining
Edit2: And don't bother replying to this comment, I'll update you on this if I be able to reproduce and debug it ;) and thanks for your great module

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Weirdly it seems changing the order of modules and putting this one at the top of nuxt modules inside nuxt.config.js fixed it somehow and I have no idea why,
just for more info on this my modules before and after are listed below:
Before:

    // Doc: https://bootstrap-vue.js.org
    'bootstrap-vue/nuxt',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/proxy',
    'cookie-universal-nuxt',
    'vue-sweetalert2/nuxt',
    '@nuxtjs/toast'
  ],

After (somehow fixed with this):

    'cookie-universal-nuxt',
    // Doc: https://bootstrap-vue.js.org
    'bootstrap-vue/nuxt',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/proxy',
    'vue-sweetalert2/nuxt',
    '@nuxtjs/toast'
  ],

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

@jd1378 I haven't got any idea why it didn't work in that particular order. Happy that you sorted this out! Maybe those plugins run as they are declared and the cookie-universal plugin wasn't registered yet, but this is just a wild guess :)

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Hi @microcipcip ,
I don't know what is really happening , but it seems that changing the order wasn't doing anything good for it ,
I figured it works sometimes and doesn't work sometimes without any reason.
I try to figure out whats happening and report back to you but I don't think I be able to any time soon as It just works and stops working without any change to nuxt.js config or packages.

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

hI @jd1378. Then you may have to share some code, there may be something that is not obvious that may be breaking the script. Also, are you using Nuxt generate? Several people had issues with it.

Another possibility is that you may have to delete node_modules and reinstall everything, given the random behaviour maybe there is some corruption in the file system.

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

Where did you log the requests headers, from axios? Sharing the code where the cookie cannot be found may help solve this issue.

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Hi @microcipcip.
No I'm not using Nuxt generate, I do yarn build and yarn start for production and use yarn dev for local development.
I was logging the headers inside my auth middleware, and the middleware is set inside nuxt.config.js
I try to setup the logging inside my auth middleware again and send the code soon. I'll also test deleting the node_modules folder and installing packages again after logging.
thanks for your help

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

this is how I was doing it:

export default async function({
  store,
  app: { $axios, $storage, $router },
  route,
  redirect,
  req
}) {
  const token = $storage.tokenService.get();

  if (token) {
    console.log('+++++++++++ Token');
  } else if (req) {
    console.log('----------- Token');
    console.log(req.headers);
  }

  if (process.server) {
    if (token) {
      try {
        store.commit('user/setToken', token);
        await store.dispatch('user/getUser');
        store.commit('user/setAuthState', true);
        // keep user up to date after loading locally
      } catch (error) {
        store.commit('user/setToken', '');
        store.commit('user/setUser', {});
        store.commit('user/setAuthState', false);
        if (process.server) {
          return redirect({ name: 'login' });
        }
      }
    } else {
      store.commit('user/setAuthState', false);
    }
  }

  const routeAuth =
    route.matched.map((r) => {
      return r.components.default.options
        ? r.components.default.options.auth
        : r.components.default.auth;
    })[0] || '';

  if (routeAuth === 'anonymous' && store.state.user.authenticated) {
    if (process.server) {
      return redirect({
        name: 'index'
      });
    } else {
      return $router.push({ name: 'index' });
    }
  }

  if (routeAuth === 'authenticated' && !store.state.user.authenticated) {
    if (process.server) {
      return redirect({
        name: 'login'
      });
    } else {
      return $router.push({ name: 'login' });
    }
  }

  const requiredRoles =
    route.matched.map((r) => {
      return r.components.default.options
        ? r.components.default.options.roles
        : r.components.default.roles;
    })[0] || [];
  if (
    requiredRoles.length &&
    !requiredRoles.includes(store.getters['user/role'])
  ) {
    if (process.server) {
      return redirect({
        name: 'index'
      });
    } else {
      return $router.push({ name: 'index' });
    }
  }
}

this is my storage:

const USER_KEY = 'user';
const TOKEN_KEY = 'accessToken';

const UserService = {
  get() {
    if (process.server) {
      return {};
    }
    return JSON.parse(localStorage.getItem(USER_KEY));
  },

  set(user) {
    if (process.server) {
      return;
    }
    localStorage.setItem(USER_KEY, JSON.stringify(user));
  },

  remove() {
    if (process.server) {
      return;
    }
    localStorage.removeItem(USER_KEY);
  }
};

const TokenService = ($cookies) => ({
  get() {
    return $cookies.get(TOKEN_KEY);
  },
  set(token) {
    const expireDate = new Date();
    expireDate.setMonth(expireDate.getMonth() + 1);
    $cookies.set(TOKEN_KEY, token, { sameSite: 'Lax', expires: expireDate });
  },
  remove() {
    $cookies.remove(TOKEN_KEY);
  }
});

export { UserService, TokenService };

also I tried getting cookies directly inside the middleware using $cookies, but result was the same.
right now , again, it's working properly.

I have a guess that maybe pwa module or workbox service worker that is installed on browser is causing issue somehow but the weird thing is even if they are causing it, why my cookie was available in request headers in the log.

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

Thanks for the example, it is a kind of complex setup, it is difficult to understand where the problem is without seeing the whole project, but I hope you won't get this issue again.

It never happend to me that this cookie library was not able to get a cookie from either server or client when nuxt generate was not used.

BTW, where do you initialize TokenService? Is that inside a server middleware?

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

I initialize it inside a plugin, here is the code:

import { UserService, TokenService } from '@/services/storage.service';
export default ({ app: { $cookies } }, inject) => {
  const storage = {
    userService: UserService,
    tokenService: TokenService($cookies)
  };

  inject('storage', storage);
};

and in nuxt config it's the first plugin to load on both server and client, so it's available everywhere

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

my guess got confirmed a bit only, because I saw it was happening with the production server, I cleared the browser data and it got fixed,
So I think it really has something to do with PWA module somehow

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

@jd1378 I see, if done in that why I don't see why cookie-universal-nuxt should not work, I guess it may be an issue with PWA as you suspected.

The cookie-universal-nuxt module is really simple and it's just a wrapper over cookie-universal script, the code is pretty much a plugin like this:

import cookieUniversal from 'cookie-universal'

export default ({ req, res }, inject) => {
  inject('cookies', cookieUniversal(req, res, true)) 
}

So if in that req object the cookie headers are present, the cookie-universal script should be able to read it.

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

I see, then the only way to find out is to debug the server when it happens again. while I was looking at cookie-universal I was thinking maybe somehow on that certain request the isNeither becomes true, I'm just guessing and don't know if it be possible
I'll let you know if I find anything new
Thanks for your help

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

NP, I think that isNeither won't happen if you're not in nuxt generate mode.

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Can you give me a brief explanation of why isNeither happens in nuxt generate mode ?
Edit: Sorry, I didn't bother to think, I got why, no need to answer this.
Edit2: Nope, I didn't get it, I guess I need your info 😄

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Also the workbox caching strategy is network first, if knowing that does any help

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

@jd1378 isNeither happens because cookie-universal is unable to understand if the environment is the server (where cookis arrive from req and res) or the client (where the cookies come from the DOM), so I had to disable cookie-universal during nuxt generate as it was throwing errors.

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

So It did happen again and I was able to set a breakpoint and check my stuff
It seems that somehow (because that I wasn't using path:'/' when setting cookie) , another cookie with the same name, but different path (when loading the path) , with empty value is set in the header before the cookie with correct value, I don't know maybe because when getting the cookie for the path it didn't exist and it created an empty one for me ? if it's the case, should it not be doing that ? And I'm not sure if it's the module doing that or my human error (It's probably me)
anyway , adding a path: '/' when setting the cookie fixed the problem I guess (hopefully)
thanks for reading and helping me along the way

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

@microcipcip nope , the issue wasn't in the cookie path in set cookie, investigating

Edit: Despite setting the path only to '/' , the cookie that is set with empty value has the path with '/admin' value
I thought then the server shouldn't be setting any cookie, since that the client will Always set the cookie when doing login
So I wrapped my set cookie function with if (process.browser) {} and I'm still getting the issue.
Any idea whats messing this up ?

Edit:
Sorry, Since I'm not very sure that it happened again still after the fix or not, No need to look into this if you think there's no problem with your code till I get this behavior again and debug further. sorry about bothering you about this

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

In the cookie-universal script there is this default for set: set(name = '', value = '', opts = { path: '/' }), so if you don't pass the options object it will default to set the cookie to the path /. If you DO pass an object without path it will work only in the page you are currently, for example if you set it on mysite.com/login, the cookie will not be available in any other path, so on mysite.com/about it won't be there.

Going back to your examples, if you have something like $cookies.set(TOKEN_KEY, token, { sameSite: 'Lax', expires: expireDate });, you may want to add the path there and in any cookie that you set, so that it doesn't matter in what page you are in, this will allow you to access the cookie everywhere.

Apart from that, there is no issue that I am aware of, as you can see the lib has 26k downloads per week so someone should have spotted an error by now. Not that is entirely impossible to have bugs obviously. Hopefully you'll solve your problem, if not, let me have a way of reproducing the error so that I can debug it.

from cookie-universal.

jd1378 avatar jd1378 commented on August 16, 2024

Thanks for the info, It seems that it was the case with not passing the path to set cookie then,
And You are right, Sorry about that, I'll provide a way to reproduce if I encounter any bug next time.
thank you a lot

from cookie-universal.

microcipcip avatar microcipcip commented on August 16, 2024

NP :)

Happy coding!

from cookie-universal.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.