GithubHelp home page GithubHelp logo

microcipcip / cookie-universal Goto Github PK

View Code? Open in Web Editor NEW
521.0 8.0 40.0 858 KB

Universal cookie plugin, perfect for SSR

JavaScript 93.13% HTML 6.87%
universal-cookie ssr-cookie node-cookie browser-cookie cookies cookie cookie-connect cookie-express nuxt-cookie vue-cookie

cookie-universal's Introduction

npm (scoped with tag)

You can use cookie-universal to set, get and remove cookies in the browser, node, connect and express apps. cookie-universal parse cookies with the popular cookie node module.

npm (scoped with tag)

You can use cookie-universal-nuxt to set, get and remove cookies in both client and server side nuxt apps. cookie-universal-nuxt parse cookies with the popular cookie node module.

cookie-universal's People

Contributors

amoutonbrady avatar bblanchon avatar darthf1 avatar dependabot[bot] avatar egorkaru avatar hiswe avatar ivopereira avatar microcipcip avatar rchl avatar runnez avatar sapfear avatar stephenjason89 avatar victorgarciaesgi avatar victortotem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie-universal's Issues

Issues with this module

I've started to use this module, and have a middleware function for logging in. Currently, this is what I'm trying to use:

this.$cookies.set('user', context, {
    maxAge: 604800000
});

It seems nothing happens after this, not the redirect, not the console logs, nothing.

I'm also trying to use this in my Navbar.vue component to get the user and set the user display/login display:

<template>
    <div>
        <div class="contain navbar">
            <nuxt-link class="item logo" to="/">
                Website
            </nuxt-link>
            
            <nuxt-link class="item" to="/about">About</nuxt-link>

            <div class="right">
                <template v-if="!user">
                    <nuxt-link class="item" to="/login">Login</nuxt-link>
                </template>
                <template v-else>
                    <nuxt-link class="item" to="/user">{{ user.username }}</nuxt-link>
                </template>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    mounted () {
        const user = this.$cookies.get('user');
        
        if (!user) {
            return { user: null }
        } else {
            return { user }
        }
    }
}
</script>

But that doesn't work either.

Can I get some help with this?

vue.d.ts doesn't honor `alias

file: fcee0e1

Hi vue.d.ts doesn't seem to honor alias

// tsconfig.json
module.exports = {
 modules: [
    //...,
    ['cookie-universal-nuxt', { alias: 'cookiez' }],
    //...
]
}
// some-comp.vue 

// <script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator';
  @Component
  export default class SomeComp extends Vue {
    someFn (t) {
      let gaId = this.$cookiez.get("_ga");
    }
  }
// </script>

plugin working on the localhost, not working on production !!

Thanks for this easy plugin for nuxt, i am using this plugin in my important project.
My question is that, the plugin is working fine on my localhost, but when i take for build in the production, its stops working ( does not delete the cookies ). Any ideas ???

argument val is invalid

Hello,

In production environment, with cookie-universal-nuxt, sometimes a bug happens with this stacktrace :

TypeError: argument val is invalid
    at Object.n [as serialize] (/srv/nodejs/20.5.1-RC/node_modules/cookie-universal/dist/cookie-universal-common.js:1:3447)
    at t.headers.Cookie.Object.keys.reduce (server.js:1:476394)
    at Array.reduce (<anonymous>)
    at t.interceptors.request.use.t (server.js:1:476347)
    at process._tickCallback (internal/process/next_tick.js:68:7)

I think that is cookie library that raised this error here : https://github.com/jshttp/cookie/blob/b223a3447666fbdabc0ff8b3583081c22fd7c4e7/index.js#L116

But I fail to reproduce the bug in dev/local environment, I'm a bit lost with the dist, the lib, the build, and finally with the sources actually executed.

Is there a good way to investigate this bug ?
Do I check and exclude some misformatted cookies ?
Should I try ... catch my uses of cookie-universal-nuxt set or get methods ?

Regards

Error running nuxt generate

When running npm run generate the following error occurs:

Cannot detect env, something went wrong!

I'm using nuxt 1.4.0

option expires in invalid

when i use expiration in my code:

 this.$cookies.set('cookie-consent', this.cookieConsent, {  expires: new Date().getFullYear() + 1 })

i get this error message:

option expires in invalid

Adding Typescript Definitions

I added typescript definition to nuxt.config.ts. However, it throws me error saying Property $cookies doesn't exists.

Here's my tsconfig.json:

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "lib": ["esnext", "esnext.asynciterable", "dom"],
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "allowJs": true,
        "sourceMap": true,
        "strict": false,
        "allowSyntheticDefaultImports": true,
        "noImplicitAny": false,
        "noEmit": true,
        "baseUrl": ".",
        "resolveJsonModule": true,
        "paths": {
            "~/*": ["./*"],
            "@/*": ["./*"]
        },
        "types": [
            "@nuxt/vue-app",
            "@types/node",
            "@nuxtjs/axios",
            "cookie-universal-nuxt"
        ]
    }
}

Please help.

is there any changelog ?

Hi
I've been updating one of my project's recently and I was wondering if there's a changelog kept anywhere (or I couldn't find it) ? I find it useful when updating a project dependencies to see what they have fixed and what new features they got
thank you again for this great module

$Cookies cannot get cookie in pages other than index Nuxt.js

Hi
I don't know why is this happening, but I can get my access token from cookie in SSR on request to index page, but no other page works.
I logged the headers when the token is unavailable through $cookies, and the cookies was available in request headers, so I think there might be a problem with the module.
I ran yarn upgrade and tested it again before posting this issue so to make sure I'm running on latest version.
I'll provide more info if any is needed.

httpOnly and secure option not working please help!!!

below is the code how I am enabling cookies in actions.js in Nuxtjs project

await this.$axios
        .post(`/post_login/`, payload)
        .then(response => {
          if (response.status == 200) {
            this.$cookies.set('at', response.data.access_token, {
              opts: { httpOnly: true, secure: true }
            });
            this.$cookies.set('rt', response.data.refresh_token, {
              opts: { httpOnly: true, secure: true }
            });
            dispatch('GET_ME', { at: response.data.access_token });
            commit('SET_USER', response.data);
          }
        })

any one can help???
One more question is this secure and httpOnly option tick marked(enabled) on localhost too if above code written??

Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError

Hi @microcipcip ,

I have kind of a page

<template>
    <div>
        {{ token }}
        {{ title }}
        <a href="/product">go to page</a>
    </div>
</template>
<script>
import axios from 'axios'

export default function({app}) {
    async asyncData ({ params }) {
        //window.alert(this.$cookies.get('token'))
        const { data } = await axios.get(process.env.baseUrl+'v1/toko/3/produk')
        return { title: data, token:app.$cookies.get('token') }
    },
    mounted(){
       console.log(this.$store.state.stars)
    }
}
</script>

Unfortunately it produced an error

Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError

How do I solve this kind of issue?
Any helps would be appreciated.

Thank you.

why? app.$cookies is undefined in nuxt

my code:
async nuxtServerInit({ commit }, { req, app }) {
global_.webUrl = req.headers.host;

app.$cookies.set('web_url', req.headers.host);

}

result:

TypeError
Cannot read property 'set' of undefined

Expire Date is Too Short

Hello, i'im adding any cookie like that;

this.$cookies.set('COOKIE_KEY', this.$store.state.COOKIE_VALUE, {
    path: '/',
    expires: new Date(new Date().getTime() + 1000 * 3600 * 24 * 30),
});

but this is adding my cookie with wrong times, maximum 7 days.
If i add smaller than 7 days it works, but not working bigger than 7.
I didn't solve this issue.

nuxt.config.js

...
modules: [
    ['cookie-universal-nuxt', {path: '/'}]
],
...```

Nuxt 2.0 incompatibility

Hi, thanks for this.

I'm getting an error on nuxt 2.0 version for this when added into modules:

× fatal TypeError: request.charCodeAt is not a function
  at Function.Module._resolveLookupPaths (internal/modules/cjs/loader.js:408:15)
  at Function.Module._resolveFilename (internal/modules/cjs/loader.js:574:20)
  at Nuxt.resolveModule ...
  at process._tickCallback (internal/process/next_tick.js:68:7)
  at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
  at startup (internal/bootstrap/node.js:279:19)
  at bootstrapNodeJSCore (internal/bootstrap/node.js:696:3)

Object doesn't support property or method 'set'

Hello, I'm having problems in IE11, it gives me the error in the title.
This is the line causing the problem:
this.$cookies.set('privacyCookie', true)

Seems to work fine in every other browser (haven't checked older than IE11 though).

I have tried updating to the latest version (2.0.14)

Any suggestions what I should do?

Thanks!

Error in types with typescript 3.7

In my code I do something like:

import CookieUniversal from 'cookie-universal';

class Foo {
    constructor() {
        this.cookieStorage = CookieUniversal(this.context.req, this.context.res);
    }
}

and that triggers a Typescript error:

Declaration emit for this file requires using private name 'ICookie' from module '"/../node_modules/cookie-universal/types/index"'. An explicit type annotation may unblock declaration emit.

I won't claim that I fully understand it, but I believe it means that ICookie is required to be public/exported if I want to assign it to a variable/property and use it later.

Cannot read property '$cookies' of undefined

Hello,

Nuxt-config.

modules: [
'bootstrap-vue/nuxt',
'@nuxtjs/pwa',
'cookie-universal-nuxt',
'@nuxtjs/toast',
],

Using NUXT 2.4.5
cookie-universal-nuxt: "^2.0.14",

I checked the other issues but could not find any answers that worked for me.

I created a middleware in NUXT and added this code:

export default function () {
  const CookieIsLoggedIn = this.$cookies.get('isLoggedIn');
  const CookieAccessToken = this.$cookies.get('accessToken');
  const CookieRid = this.$cookies.get('rid');

  if ((CookieIsLoggedIn === true) && (CookieAccessToken !== undefined) && (CookieRid !== undefined)) {
    commit('isLoggedIn', CookieIsLoggedIn);
    commit('setToken', CookieAccessToken, CookieRid);
  } else {
    commit('isLoggedIn', false);
    this.$cookies.removeAll();
  }

Unfortunately when I run the command "nuxt" i get this error:
Cannot read property '$cookies' of undefined

I am only trying to get the cookies from the client side.

I forgot to mention that your cookie plugin works well within my vuex store, it is just in the middleware folder that it does not working.

Thank you.

Breaks in Internet Exlorer 11. Doesn't get transpiled?

Seems the module somehow doesn't get transpiled and thus breaks in IE11. Using this in the latest Nuxt.js (v2.3.0).

image

Not sure if this is a problem with the module or with Nuxt itself, don't have any problems with other modules I use.

Error: Can't set headers after they are sent.

Hello.
In SSR middleware i sent request in promise. In catch block i called app.$cookie.remove and got Error: Can't set headers after they are sent. I know, that in this moment i try to edit response header. But how i must use remove function in this situation?

Cannot read property '$cookies' of undefined

Hello everyone, I'm new to nuxt, I can't resolve this error, someone can help me,

TypeError :
Cannot read property '$cookies' of undefined

nuxt.config.js

 modules: [
    '@nuxtjs/axios',
    '@nuxtjs/dotenv',
    'cookie-universal-nuxt',
  ],

store/pages/state.js

export default () => ({
  user_conf: this.$cookies.get('config-app'),
})

Avoid implicit JSON?

In get(...) there is the following code:

  try {
    return JSON.parse(cookie)
  } catch(err) {
    return cookie
  }

This code is likely to cause bugs for the following reasons

  1. Users can modify cookies. This means a malicious user can change their cookie to be a JSON string and now a method that I expect to return a string returns and object. This isn't a security problem on its own, but it seems like the sort of thing that when combined with something else could get the program to go down unindented path.
  2. It's an ``in-band'' encoding which collides with strings I might want to store. I can test my program a lot, and not put anything that's valid JSON in my cookies, but then I accidentally put a string which is valid JSON in my cookie. Now when it gets decoded my program behaves in an unintended way, because it's dealing with a value other than a string.

How do I access $cookies in the store?

I am trying to convert code that was client-only to use this library, but I cannot get it to work.

Original code was:

export const getters = {
  getCookie() {
    return window.$nuxt.$cookies.get('token')
  }
}

I've tried changing window.$nuxt.$cookies to app.$cookies and this.$cookies but neither of them work, I just get undefined. I saw somewhere else that I might need to get app from context, but context isn't defined either. I'm stumped.

cookies not readable from middleware client side

I have following middleware:
export default function (context) { process.server? console.log(context.app.$cookies.get('JSESSIONID')): console.log(this.$cookies); }
On the first load, it is fine, because the middleware is loaded on server side, so I am able to retrieve the cookies
When I navigate between pages, however, middleware is executed client side and I am not able to access it either with context.app.$cookies or this.$cookies
console.log(context.app.$cookies) -> undefined
console.log(this.$cookies) -> app.js:304 TypeError: Cannot read property '$cookies' of undefined

On the server `cookie.get` should return what is `cookie.set`

Can you make cookies dynamic on the server, so that the following would work:

   // set foo for the very first time
   cookie.set('foo', 123); // the cookie will be set on the client once the page is served
   
   cookie.get('foo') // returns undefined ; expected 123

I know it will be a bit hacky but I think it is useful.

Regards :}

[Question] How to use the plugin

Hi,

I am sorry because post question here. Currently i have seen we have two ways to call the cookie which is either use this or app. If let say i'm just call using in client which is using this, do I need to call it again using app to ensure both client and server have same cookie? or actually it will be both in server and client?

Thank you and have a nice day!

set default options not work

Hello

How i can set default option for cookie-universal-nuxt ,

this not work for me

  modules: [
    {
      src: 'cookie-universal-nuxt',
      options: {
        alias: 'cookies',
        path: '/',
        expires: new Date(Date.now() + 604800), // 7day
        // maxAge : ,
        // httpOnly : null,
        domain: '.domain.com',
        // encode : ()=>{},
        sameSite: null,
        secure: true
      }
    },

thank you.

$cookie is undefined in app

"nuxt": "^2.11.0"
I added module 'cookie-universal-nuxt' in "modules" section of nuxt config at first position.
In serverMiddleware config added my middleware link.
Code in server middleware:

export default ({ app }) => {
    console.log(app.$cookie);
}

And app.$cookie is undefined

Accessing app.$cookie in Nuxt store

Hi,

I'm attempting to store an external api response in a cookie and am struggling to figure out how to do so within the Nuxt store. I'm new to Nuxt (and Vue.js) so many of the key concepts still go over my head.

In my store folder, I have a store.js file with the following action:

export const actions = {
  getResponse: ({ commit }, data ) => {
      axios.post(
        `http://some.url/some_request`
      ).then(( response ) => {
      var response_details = {
        response_variable: response.data.variable
      };
      commit("setResponse", response_details );
      app.$cookie.set("cookie", response_details , {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
      });
    })
  }
}

However, app doesn't exist and throws an error. Every example I see says to access things this way, but I've not been able to figure out how to access the app context.

Thanks ...

Nuxt generate and vuex store issuees

Hi!

I'm trying to create a shop website with nuxt. I need to save a cart ID somewhere, so whenever you leave the page and come back, items in your cart are still there. Here is the code in store.js:

    actions: {
      async nuxtServerInit({ commit }, { app }) {
        const shopCheckoutID = app.$cookies.get("KBCheckoutID"); // Get cart ID from cookies
        let checkout = {};
        if (shopCheckoutID) { // If cookie with cart ID is found
          checkout = await app.$shopifyClient.checkout.fetch(shopCheckoutID); // Get the cart contents from API
          if (checkout.completedAt) { // If the purchase is completed
            checkout = await app.$shopifyClient.checkout.create(); // Create a new cart
          }
        } else { // If cookie with cart ID is not found
          checkout = await app.$shopifyClient.checkout.create(); // Create a new cart
        }

        let shop = {
          checkout: await checkout,
          products: await app.$shopifyClient.product.fetchAll(),
          shop: await app.$shopifyClient.shop.fetchInfo()
        };

        await app.$cookies.set("KBCheckoutID", shop.checkout.id); // Save the cart ID in cookies

        commit("initShop", shop); // Push the shop object to vuex store
      }
    }

Basically I check whether the ID in cookies exists, if it does, fetch the cart, if it doesn't create a new cart (or at least that's what I intend to do).

The problem I'm facing - this works perfectly in nuxt dev mode, but when I use nuxt generate and host it on a server it doesn't work - no cookie is saved in the browser. Is this a limitation of nuxt generate? Any help would be kindly appreciated!

Update cookie dependency version

@microcipcip Hi, we have been trying to add support for SameSite cookie option for our repos. link
But for some cases, we want to enforce the None value for SameSite option which got supported only from cookie-0.4.0 link, as this is the only update in the latest version, we hope that it's not much trouble to update the cookie dependency for cookie-universal-nuxt.
What do you think?
Of course, I would be more than happy to contribute to the project(if needed).

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.