#Trying to read cookie using js-cookie but getting undefined

19 messages · Page 1 of 1 (latest)

chilly merlin
#

I am trying to read a cookie(which i have set in the backend) in the frontend but getting undefined

Here is the backend code

async createUser (req, res){
        const newUser = new userModel(req.body)
        try {
            await newUser.save()
            const token = jwt.sign({ _id: newUser._id }, process.env.SECRET_KEY, { expiresIn: '60 days' });
            // setting cookie 
            res.cookie('socialAuthToken', token, { maxAge: 900000, httpOnly: true });
            console.log(res.cookie)
            return res.status(200).json({
                user: newUser,
                message: "Successfully signed up!"
            })        
        } catch(e){
            console.log(e)
            return res.status(400)
        }
        res.end()
    }

I have tested the backend using postman and it is storing the socialAuthToken in the cookies but when I am using the react frontend to get the cookie it showing undefined

Frontend code:

import React, { useState, useEffect } from 'react';
import axios from 'axios'
import Cookies from 'js-cookie'


function ShowUser(){
  var value = Cookies.get('socialAuthToken')
  console.log(value)
}
daring frigate
#

You have set HttpOnly flag for that cookie, which prevents client JS from reading that cookie

#

Can you see this cookie in browser devtools?

signal vapor
#

You don't need to read the cookie for anything. You can make http requests with it automatically

chilly merlin
chilly merlin
signal vapor
#

You can send it back when logging in or do what everyone else does: read it from /api/users/me

#

(or the id)

chilly merlin
signal vapor
#

Only server can read it. That's the point.

#

Otherwise bad scripts and user extensions can steal it

chilly merlin
#

Okay so i should read the cookie in the backend and login the user accordingly?

chilly merlin
#

thanks

chilly merlin
#

I did some changes to backend and frontend.
The backend to read the user looks like this:

async getUserById (req, res){
        const token = req.cookies.socialAuthToken
        const data = jwt.verify(token, process.env.SECRET_KEY);
        const id = data._id
        // console.log(id)
        try {
            let user = await userModel.findById({_id:id})
            // console.log(user)
            if (!user){
                res.status(400).json({
                    error: "User not found"
                })
                return;
            }
            user.password = undefined
            res.json(user)
            res.end() // important otherwise 'ERR_HTTP_HEADERS_SENT' coming as multiple response are getting sent
        } catch (err) {
            return res.status(400).json({
                    error: "Could not retrieve user"
                })
            }
    }

And the frontend looks like this:

import React, { useState, useEffect } from 'react';
import axios from 'axios'

const baseUrl = 'http://localhost:5000/socialApp/api/users/me'

function ShowUser(){
    const [user, setUser] = useState({});

    useEffect(() => {
        console.log("use effect")
        axios.get(baseUrl).then((res) => {
                console.log("reached")
                console.log(res)
                // setUser(Object.values(res.data))
        })
      },[]);
}

export default ShowUser

But on the console it throws unauthorized 401 error .

daring frigate
#

If frontend receives 401, then i think it's not coming from backend code you showed, because it responds with 400 (not 401) in error case

chilly merlin
#

So what could be the issue?