Nate
Nate

Reputation: 95

Cookies.get() returns undefined

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

Upvotes: 2

Views: 2513

Answers (1)

Fedor Petrov
Fedor Petrov

Reputation: 31

Actually, you are adding secure: true parameter in Cookies.set function and calling baseURL: 'http://localhost:8000/' without HTTPS protocol, that's the reason. So, you just need to set secure: false

The Secure attribute limits the scope of the cookie to "secure" channels (where "secure" is defined by the user agent). When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS) [RFC2818]).

Upvotes: 3

Related Questions