I’ve got a function that creates a cookie (I’m using sveltekit):
event.cookies.set(AUTH_TOKEN_KEY, response.data.token, {
// send cookie for every page
path: '/',
// server side only cookie so you can't use `document.cookie`
httpOnly: false,
// only requests from same site can send cookies
// https://developer.mozilla.org/en-US/docs/Glossary/CSRF
sameSite: 'strict',
// only sent over HTTPS in production
secure: process.env.NODE_ENV === 'production',
// set cookie to expire after a month
maxAge: 60 * 60 * 24 * 30,
})
the cookie is successfully created (see image):
championship-access-token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlYXQiOiIyMDIzLTA1LTIyVDAxOjI4OjMwLjk0MzAwMTE3MloiLCJpYXQiOjE2ODQ3MTY5MTAsImlkIjo3fQ.VaVfzgnib0DhzRO8jUJ-X_2BRIiAGXIq8eEQOs85anI localhost / 6/20/2023, 8:55:10 PM 192 B ✓ Strict
Now, I’ve created an axios interceptor since I want to retrieve the token stored in the cookie and attach it to my requests. The problem is that I cannot access the cookie. I’m using js-cookie
, and the interceptor looks like this:
import axios from "axios";
import Cookies from 'js-cookie';
export const app = axios.create({
baseURL: "http://127.0.0.1:8080/api/v1",
timeout: 1000,
params: {},
});
app.interceptors.request.use(
config => {
console.log("interceptor -> retrieving cookie:");
Cookies.set("test123", "asdasdasd")
console.log(Cookies.get(AUTH_TOKEN_KEY));
console.log("test cookie: ", Cookies.get("test123"))
console.log("cookie: ", Cookies.get(AUTH_TOKEN_KEY));
console.log("ALL COOKIES", Cookies.get())
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error)
}
);
In the code above I’m not trying yet to attach the value of the cookie, I’m simply trying to retrieve it at the moment but it’s always undefined
. I tried to create a new cookie using js-cookie
but doesn’t seem to work. Notice that the original cookie was created using a cookie helper from Sveltkit which I cannot access at this point (or at least I don’t know how since it’s only accessible from server side files), reason why I decided to use js-cookie
.
Any idea what’s going on? Perhaps is the import
the one that I got wrong? I already tried:
import * as
Cookies from 'js-cookie'
yet the result is the same.
One more thing which I don’t know if it’s relevant to the question: notice this param used to create the cookie:
httpOnly: false,
even though it is set to false
, the cookie is set as httpOnly
(see screenshot).
Thanks