Giter VIP home page Giter VIP logo

vue-cookies's Introduction

vue-cookies

A simple Vue.js plugin for handling browser cookies

Installation

Browser

  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/[email protected]/vue-cookies.js"></script>

Package Managers

npm install vue-cookies --save

// require
var Vue = require('vue')
Vue.use(require('vue-cookies'))

// es2015 module
import Vue from 'vue'
import VueCookies from 'vue-cookies'

// default options config: { expires: '1d', path: '/', domain: '', secure: '', sameSite: 'Lax' , partitioned: false}
Vue.use(VueCookies, { expires: '7d'})

Api

  • vue2 :
    • [this | Vue].$cookies.[method]
  • vue3 :
    • Composition API: $cookies.[method]
        // js
        const $cookies = inject('$cookies');
        // ts
        const $cookies = inject<VueCookies>('$cookies'); 
      
    • Options API : this.$cookies.[method]

  • Set global config
$cookies.config(expires[,path[, domain[, secure[, sameSite, [partitioned]]]])  // default: expires = 1d, path = '/', domain = '', secure = '', sameSite = 'Lax', partitioned = ''
  • Set a cookie
$cookies.set(keyName, value[, expires[, path[, domain[, secure[, sameSite, [partitioned]]]]]])   //return this
  • Get a cookie
$cookies.get(keyName)  // return value                             
  • Remove a cookie
$cookies.remove(keyName [, path [, domain]])  // return false or true
  • Exist a cookie name
$cookies.isKey(keyName)  // return false or true
  • Get All cookie name
$cookies.keys()  // return a array

Example Usage

set global config

// 30 day after, expire
Vue.$cookies.config('30d')

// set secure, only https works
Vue.$cookies.config('7d','','',true)

// 2019-03-13 expire
this.$cookies.config(new Date(2019,03,13).toUTCString())

// 30 day after, expire, '' current path , browser default
this.$cookies.config(60 * 60 * 24 * 30,'');

support json object

var user = { id:1, name:'Journal',session:'25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX' };
this.$cookies.set('user',user);
// print user name
console.log(this.$cookies.get('user').name)

set expire times

Suppose the current time is : Sat, 11 Mar 2017 12:25:57 GMT

Following equivalence: 1 day after, expire

Support chaining sets together

 // default expire time: 1 day
this.$cookies.set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX")
        // number + d , ignore case
        .set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1d")
        .set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX","1D")
        // Base of second
        .set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX",60 * 60 * 24)
        // input a Date, + 1day
        .set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", new Date(2017, 03, 12))
        // input a date string, + 1day
        .set("user_session","25j_7Sl6xDq2Kc3ym0fmrSSk2xV2XkUkX", "Sat, 13 Mar 2017 12:25:57 GMT")

set expire times, input number type

this.$cookies.set("default_unit_second","input_value",1);            // 1 second after, expire
this.$cookies.set("default_unit_second","input_value",60 + 30);      // 1 minute 30 second after, expire
this.$cookies.set("default_unit_second","input_value",60 * 60 * 12); // 12 hour after, expire
this.$cookies.set("default_unit_second","input_value",60 * 60 * 24 * 30); // 1 month after, expire

set expire times - end of browser session

this.$cookies.set("default_unit_second","input_value",0);          // end of session - use 0 or "0"!

set expire times , input string type

Unit full name
y year
m month
d day
h hour
min minute
s second

Unit Names Ignore Case

not support the combination

not support the double value

this.$cookies.set("token","GH1.1.1689020474.1484362313","60s");  // 60 second after, expire
this.$cookies.set("token","GH1.1.1689020474.1484362313","30MIN");  // 30 minute after, expire, ignore case
this.$cookies.set("token","GH1.1.1689020474.1484362313","24d");  // 24 day after, expire
this.$cookies.set("token","GH1.1.1689020474.1484362313","4m");  // 4 month after, expire
this.$cookies.set("token","GH1.1.1689020474.1484362313","16h");  // 16 hour after, expire
this.$cookies.set("token","GH1.1.1689020474.1484362313","3y");  // 3 year after, expire

// input date string 
this.$cookies.set('token',"GH1.1.1689020474.1484362313", new Date(2017,3,13).toUTCString());
this.$cookies.set("token","GH1.1.1689020474.1484362313", "Sat, 13 Mar 2017 12:25:57 GMT ");

set expire support date

var date = new Date;
date.setDate(date.getDate() + 1);
this.$cookies.set("token","GH1.1.1689020474.1484362313", date);

set never expire

this.$cookies.set("token","GH1.1.1689020474.1484362313", Infinity);  // never expire
// never expire , only -1,Other negative Numbers are invalid
this.$cookies.set("token","GH1.1.1689020474.1484362313", -1); 

remove cookie

this.$cookies.set("token",value); // domain.com and *.doamin.com are readable
this.$cookies.remove("token"); // remove token of domain.com and *.doamin.com 

this.$cookies.set("token", value, null, null, "domain.com"); // only domain.com are readable
this.$cookies.remove("token", null, "domain.com"); // remove token of domain.com 

set other arguments

// set path
this.$cookies.set("use_path_argument","value","1d","/app");  

// set domain
this.$cookies.set("use_path_argument","value",null, null, "domain.com");   // default 1 day after,expire

// set secure
this.$cookies.set("use_path_argument","value",null, null, null, true);

// set sameSite - should be one of `None`, `Strict` or `Lax`. Read more https://web.dev/samesite-cookies-explained/
this.$cookies.set("use_path_argument","value",null, null, null, null, "Lax");

// set partitioned
this.$cookies.set("use_path_argument","value",null, null, null, true, null, true);

other operation

// check a cookie exist
this.$cookies.isKey("token")

// get a cookie
this.$cookies.get("token");

// remove a cookie
this.$cookies.remove("token");

// get all cookie key names, line shows
this.$cookies.keys().join("\n"); 

// remove all cookie
this.$cookies.keys().forEach(cookie => this.$cookies.remove(cookie))

// vue-cookies global
[this | Vue].$cookies.[method] 

Warning

$cookies key names Cannot be set to ['expires','max-age','path','domain','secure','SameSite']

License

MIT Copyright (c) 2016-present, cmp-cc

vue-cookies's People

Contributors

adrianoleiterodrigues avatar cmp-cc avatar goatandsheep avatar lostcode7 avatar msklenica avatar noegnh avatar olivertappin avatar paulvrugt avatar szabobgabor avatar vegerot avatar xianzouxiang 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

vue-cookies's Issues

window.$cookies.get('cookie-name') // what if I have many cookies with same name?

My question is, what if I have many cookies in the same domain, but in different paths, how would I get a token from a specif path using vue-cookies?
I ask this, because when I try to do so, the window.$cookies.get('cookie-name') returns just the cookie in the path were it was called from and not the one with same name but in different paths.
I still tried window.$cookies.get('cookie-name', '/specific-path') but same result.

Thanks for your attention, and awesome contribution with vue-cookies :D

.domain.com, sub.domain.com ping pong play

Hi,
In our back-end, front-end system we like to share cookie.
In main site we set cookie including domain name as .domain.com.
This cookie is accessed by sub-domain and key are readable, but if add or edit cookie, it write sub.domain.com despite fact that we have mentioned .domain.com, by a better word it add sub. to beginning of domain, unwanted.
Why? Is there anything wrong with our code?

SameSite attribute?

I was unable to find an example on how to set the attribute “SameSite”. Is it possible to set it globally in the config?

What about per-cookie basis?

Many thanks

README typos

Thanks for plugin first!

Fix three typos in readme.md file for $cookies:

Remove a cookie
this.$cookies.remove(name[, path],domain)
Exist a cookie name
this.$cookies.isKey(keyName) // return boolean
Get All cookie name(KeyName)
this.$cookies.keys() // return a array

Samesite bug on cookie remove

Browser: Firefox 77.0.1
Issue: Cookie “mycookie” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value, without the “secure” attribute. To know more about the “sameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite

It happens when i call Vue.$cookies.remove('mycookie'); because it rewrites a cookie and sets no Samesite and no Secure flag. It's possible to solve this by just adding Secure flag to it when removing it.

Created a #57 for it

Cannot set session cookie in internet explorer 11

The cookie behavior is internet explorer is different from Chrome and Firefox. This causes a cookie that is set with "expires=0", to not be set at all, because internet explorer thinks the cookie has immediately expired. Chrome and firefox both treat "expires=0" as a session cookie.

Cookie not working on iOS

Hey guys,

vue-cookies works nice for my Android project but it doesn't on iOS.

Does anyone had the same problem?

Release 1.7

Trying to avoid installing from github, would appreciate a version 1.7 with the samesite cookie functionality. :)

set domain

// set domain
this.$cookies.set("use_path_argument","value",null, null, "domain.com"); // default 1 day after,expire
失败,域名还是没变

Error when set cookie in App.vue

I need set a JSON as cookie in my app load, in App.vue. But, localhost
works fine, in production, after a build, not working. Cookie cannot set these values..

App.vue

(...)

created() {
  const userJson = {
    name: 'Ednilson',
    id: 12032
  };
  window.$cookies.set('user', userJson);
}

(...)

After I set the default values, my vuex store get those values, immediately.

Bue, Vuex runs first, and I need runs the set cookie first before Vuex.

Anybody can helps me, please?

this.$cookies is undefined

main.js:

import VueCookies from 'vue-cookies'
Vue.use (VueCookies)

this.$cookies.set('name', 'trial')

error in console: this.$cookies is undefined

Improve docs for .remove()

We are building a site that uses the same login page for multiple subdomains and we were struggling with the logout action, after inspecting source code of the remove function we realised that if you don't use the same parameters for creating and deleting the cookie, it won't work.
Example:

window.$cookies.set("token", value, null, null, "domain.com");

this would not work:

window.$cookies.remove("token");

you need to do:

window.$cookies.remove("token", null, "domain.com");

Great library! Keep up the good work

getting an extra dot(.) in cookie domain

Hi i have a scenario where i have to create a cookie with the current hostname as domain, but it's adding an extra dot(.) before the hostname.

let domain = location.hostname
window.$cookies.set('name', 'value', '12h', '/', domain)

Ex: expected domain for cookie: google.com actual domain name set in cookie .google.com

Thanks

Error in example

In the usage example it says: import Vue from 'Vue'.

This is a typo that will lead to the following error during compilation:

There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing.

It should read import Vue from 'vue'

Set Httponly flag

How can I set the httponly flag? Is it set by default with the secure flag?

Problem with getting cookies with dot in their names.

I'm having an issue where the library is not able to get cookie values or keys if the cookie name is smth like this: bar.faz

Methods like this.$cookies.get('bar.faz') and this.$cookies.isKey('bar.faz) do not seem to work.

The issue looks like it's on this line:
new RegExp('(?:^|;\\s*)' + encodeURIComponent(key).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie)

Vue cokies does not work inside an iframe

I'm working on some legacy code one of my ex-colleague left me.

Inside a router guard, he added this check.

window.$cookies.get("token-iotbuilding")

He manually sets the cookie after he calls the authentication API.
globalLogin.$cookies.set("token-iotbuilding", response.data.user.user.token);

But when I put the entire app inside an iframe the $cookies.get always returns null

Am I doing something wrong? I never had this issue when putting a web app inside an Iframe;

I tried to set the same site to Lax too but it's just not working at all

globalLogin.$cookies.set("token-iotbuilding", response.data.user.user.token, null, null, null, null, "Lax");

so many errors in document?

  1. API shold use before: this.$cookie, not this.$cookies
    2.remove cookie shold use this.$cookie.delete(),not this.$cookie.remove()
    3.set expire times can not use,now I only use number time, it's default time unit is day, not second

vue 2.6.10 typescript

"vue-cookies": "^1.5.14",
"vue": "^2.6.10",
"vue-class-component": "^7.1.0",

gives eror:

Property 'install' is missing in type 'VueCookies' but required in type 'PluginObject<any>'.

remove cookie from browser

Hello there, after updating to vue-cookies 1.7.1 i couldnt no longer remove a cookie from the browser using nuxt v2.13.3
in ssr mode, universal app. Had to downgrade to 1.7.0 couldnt find the reason why. window.$cookies.remove('dark-cookie');

getting TypeError: Cannot read property 'get' of undefined

hi, I had tried this , window and Vue. all of them doesnot work.
below code is inside my login.vue
created() { try { let token = this.$cookies.get('token'); constant.DEBUG ? this.$log.info('token at home page ', token) : null; if (token == null || token === '' || !this.$store.dispatch('inspectToken', this)) { alert("Please login first."); this.$router.push('/login'); } else {

below code is inside my main js
Vue.use(require('vue-cookies'));

doesn't work with base64 value for cookie

When I tried to set a base64 value for my cookie with this lib, the cookie got wrongly encoded. The = sign was replaced by its code %3D and when I tried to decode it with js function atob(), it didn't work.

Do we have a setRawCookie at the lib so things like this wouldn't happen?

Vue Modern build causes error with plugin

Hello,

I have just tried to build a modern build using the new cli3 modern build button and Chrome shows a white page with this error:
chunk-vendors.a6a3faab.js:81 Uncaught TypeError: Cannot read property 'json' of null
at o (chunk-vendors.a6a3faab.js:81)
at Function.t.use (chunk-vendors.a6a3faab.js:28)
at Object.c0d6 (app.a34e90b2.js:1)
at c (app.a34e90b2.js:1)
at Object.41cb (app.a34e90b2.js:1)
at c (app.a34e90b2.js:1)
at Module.56d7 (app.a34e90b2.js:1)
at c (app.a34e90b2.js:1)
at Object.0 (app.a34e90b2.js:1)
at c (app.a34e90b2.js:1)

The error seems to be pointing to this.json in your plugin
this.json||'"'!==u.charAt(0)||(u=u.slice(1,-1));try{var d=O[0].replace(z,decodeURIComponent)

Safari issue

We are using Vue for saving a cookie. We have the issue that cookies are not saved within Safari.
When using Google Chrome and Firefox it is completely working. Cookies are enabled in Safari so that's not an issue there.

Is there any issue known about that?
We are using a cookie.js file with the following:
`import Vue from 'vue';

import VueCookies from 'vue-cookies';

Vue.use(require('vue-cookies'));

VueCookies.config('23h');

export default VueCookies;`

Then import in the .Vue files with import cookies from '../cookies.js';
And then use it in methods with cookies.set('bearer', response.data.access_token);

Thanks in advance

Issue with setting cookies in production build

Production without breakpoint:

Production with breakpoint:

The first screenshot is taken on the current chrome. What you can see is that the cookie is not set. However, when I put in the sources of chrome a debug point and step over the code then the cookie is set.

Both images where taken in the same production build. It only occurrs when you build in production.

Any idea what the problem could be?

V1.6.0 needs to improve remove()

Global configuration:

$cookies.config("0", "/", "domain.com");

When the web runs on a.domain.com.

$cookies.set("k1", "v1");
$cookies.remove("k1");   // this will not delete K1.

you need to do:

$cookies.remove("k1", null, "domain.com");

The reason is:

remove: function(key, path, domain) {
            if (!key || !this.isKey(key)) {
                return false;
            }
           // defaultconfig.domain is not considered in domain processing
            document.cookie = encodeURIComponent(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : defaultConfig.path);
            return this;
},

Unexpected cookies being created on page reload

Firstly, thanks alot with the vue-cookies!! Its great and is really helpful. On the other hand, I am new to cookies and might not have the best understanding on how to go about this problem so I had to post it here.

To give a background, I am using vue-cookies npm to store JWT tokens to see whether the user is authenticated on reloading a page.

I will take you step by step to help you best understand the problem I am facing:

  1. When the user logs in for the first time, I use window.$cookies.set('user_token', resp.data.token, INFINITY) and resp.data.token is the JWT token I receive after making an axios call to the backend. The image below shows that there is one cookie set named user_token.
    Note: The user is directed to http://localhost:3000/

screen shot 2018-08-29 at 10 28 56 pm

  1. I reload the page and it still successfully logs the user in and shows the results shown in the image above.

  2. Now then I go to another route http://localhost:3000/user/1 which is a reusable route meaning that only the id changes while I call /user/:id to change the route. The pic below shows that it successfully lets the user access the page as the cookie set in the window is still active and matches the one in the backend

screen shot 2018-08-29 at 10 33 43 pm

  1. Now this is where my problem starts where when I reload this route http://localhost:3000/user/1 my cookie in the window changes and there are multiple cookies under the same name and this logs the user out. The pic below shows the difference in the cookie JWT values and there are multiple cookies under the same name.

screen shot 2018-08-29 at 10 36 57 pm

Note: I only set cookie when the user logs in and not during reload because the cookie is already set.
So I have no idea how the new cookie is being set with a different JWT token of its own. Would it be a bug?

Vue 3 support

Hey guys,
Is there is a plan regarding this plugin and Vue3?

Checking For Existent Cookie Returning False

Hi! Thank you for contributing this awesome module to work with cookies in Vue. I'm having an issue where calling this.$cookies.isKey('clientID') where clientID is the name of my cookie is always returning false, even though the cookie is set and I am verifying it in my dev tools. For a little more context, I'm checking for this cookie inside of a method in the methods property in a Vue component, and it is being called as the value of a v-if directive in a span. I would appreciate any pointers on resolving this issue, thanks!

Delete all cookies

Hello,

How do we delete all the cookies at once, do you have a function or do we have to create our own?

Thank you

Unexpected token is happened in v1.5.9

Hi.
We can not build the latest version(v1.5.9),
because "Unexpected token error" is happened.
Please fix this bug.

Module parse failed: Unexpected token (35:109)
You may need an appropriate loader to handle this file type.
|             var value = decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null
|
>             if(value && value.substring(0,1) === "{" && value.substring(value.length-1,value.length === "}") {
|                 try {
|                     value = JSON.parse(value)

if(value && value.substring(0,1) === "{" && value.substring(value.length-1,value.length === "}") {

Set Cookie Secure Not Working

I am trying to set a secure cookie like--
this.$cookies.set('key_name', value, -1, '/path', window.location.hostname, true);

It's not working.
But when I am trying like -
this.$cookies.set('key_name', value, -1, '/path', window.location.hostname);

this, it's working. But the content isn't secure.
How can I set secure cookies?

set expires but it no work

code:
this.$cookies.set("token","GH1.1.1689020474.1484362313","30MIN");
set cookie is ok but the expires is session
code:
this.$cookies.set("token","GH1.1.1689020474.1484362313",3);
the expires is 3day

Can't set expiry

I can't seem to set the expiry. Without it, it works fine.

this.$cookies.set('name',` 'value', 1);

how to Set this to secure and HTTPOnly flag

Hi i would like to check how to set this to Secure and HTTPOnly flag my current syntax is below but only secured

this.$cookies.set( "firstName","myName","1d",null,window.location.hostname,true);

Secure Cookie Not being Set

Hello i am setting my Cookies like this.on the HTTP/else it is working and setting a cookie while on my HTTPS server its not setting any cookies.

if (window.location.protocol == "https:"){ this.$cookies.set("firstName", "Jer", "1d",window.location.hostname,true); this.$cookies.set("lastName", "Sample", "1d",window.location.hostname,true); this.$cookies.set("companyName", "Sample Comp", "1d",window.location.hostname,true); this.$cookies.set("companyID", "VIP", "1d",window.location.hostname,true); }else{ this.$cookies.set("firstName", "Jer", "1d",window.location.hostname); this.$cookies.set("lastName", "Sample", "1d",window.location.hostname); this.$cookies.set("companyName", "Sample Comp", "1d",window.location.hostname); this.$cookies.set("companyID", "VIP", "1d",window.location.hostname); }

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.