What is the best practice for setting a cookie in vuejs? I use SSR, so I guess I can’t use localStorage.
What is the best approach here?
Setting the cookie$cookies. set() method by passing a cookie-name, cookie-value as arguments. Here is an example, that sets a cookie to the webpage by clicking the Set Cookie button. You can also set the cookie expiration time like this.
To get a cookie inside the vue component, we need to use the this. $cookies. get() method by passing a cookie-name as its argument. Note: If you set an httpOnly to the response, then you can't access it inside the vue app.
Vuex is a state management pattern + library for Vue. js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
You could use the vue-cookie or vue-cookies npm package. You can set a cookie in the created method.
created() {
this.$cookie.set("keyName", keyValue, "expiring time")
}
You can also do it in a plain JavaScript without using extensions.
Lets say you want to store a token with expiry of 24 hours inside axios
POST response.
axios
.post("url", dataToSend)
.then(function (response) {
if (response.status == 200) {
let d = new Date();
d.setTime(d.getTime() + 1 * 24 * 60 * 60 * 1000);
let expires = "expires=" + d.toUTCString();
document.cookie =
"Token=" + response.data.Token + ";" + expires + ";path=/";
}
})
.catch(function (error) {
console.log(error);
});
Use vue-cookies
To use:
<script src="https://unpkg.com/[email protected]/vue-cookies.js"></script>
<script>
$cookies.set('cookie_name', 'cookie_value');
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With