microcipcip / cookie-universal Goto Github PK
View Code? Open in Web Editor NEWUniversal cookie plugin, perfect for SSR
Universal cookie plugin, perfect for SSR
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!
"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
subj
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)
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 :}
this.$cookies.delete('key');
? not work
Hi. Not building with actual TS version.
For reference https://github.com/vuejs/vue-hackernews-2.0
There is no nuxt.config in this repo. It does not use nuxt.
How can I use cookies in a server rendered application e.g. in above application.
Please help.
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
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 set cookie on the server, shows an error: Cannot set headers after they are sent to the client.
if i try app.$cookie in nuxt vuex store have error undefined. How fix ?
Hi.
Can I remove cookie by domain option?
I want to give remove option domain not path
Thank you for great module
Hi @microcipcip ,
I have issues like the title when I run 'nuxt generate'
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
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.
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 ...
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?
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: '/'}]
],
...```
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>
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
I trying to remove "falsy" cookies (cookies that contains 0
, or false
), but I cannot.
I think this is due to:
Current workaround: set a non "falsy" value to be removable.
It will be helpful in some IDEs.
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 ???
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.
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??
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.
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?
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'),
})
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
rt
@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).
Hello, I've trie a nuxt project with your module and a module to display a cookie control notification
https://gitlab.com/broj42/nuxt-cookie-control
It seems that only one can work and it is the first one declared in the nuxt.config file.
Regards,
xavier
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!
ex) httpOnly
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
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.
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.
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.
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!
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
How should I use $cookies inside Vuex actions?
When running npm run generate
the following error occurs:
Cannot detect env, something went wrong!
I'm using nuxt 1.4.0
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.