I am using the js-cookie package to store and handle cookies in my react app. The cookie is set when the user first logs in and is visible in the Applications tab in the browser. I created a service that adds new products to the database, the cookie stores the jwt token which is then passed to the backend for verification before the user does anything. the Cookies.get() method always returns undefined within this service.
Here the code for the service
import axios from 'axios'
import Cookies from "js-cookie";
import { ProductTypes } from '../domain/entities/Product';
import { addProductResponse, getProductResponse } from '../domain/responses/productResponse';
const token = Cookies.get("authToken");
const instance = axios.create({
baseURL: 'http://localhost:8000/',
headers: {
"Content-type": "application/json",
"Authorization":`Bearer ${token}`
},
});
export const addProduct = async(formValues:ProductTypes):Promise<addProductResponse>=>{
console.log("token from react",token);
return await instance.post(`/products/create-product`,formValues).then(
(response:addProductResponse) => response)
}
This is how it is being set
const setToken = (authToken: string) => {
Cookies.set("authToken", authToken, {
expires: new Date(Date.now() + 15 * 60 * 1000),
secure: true,
});
};
Can someone kindly point out to me what i may doing wrong? PS: It is a Typescript application
Actually, you are adding
secure: trueparameter inCookies.setfunction and callingbaseURL: 'http://localhost:8000/'withoutHTTPSprotocol, that's the reason. So, you just need to setsecure: false