Search code examples
reactjscookiesgoogle-chrome-devtoolsmern

cookie sent from node backend but not shown on application tab


I am sending cookie in response from node backend to my frontend after jwt signing. In the network tab on frontend , the set-cookie is visible and the cookie is been shown , but in the application tab , the cookie is not getting shown. Why is it?

Backend Function Code for sending cookie :

import jwt from 'jsonwebtoken'

export const generateTokenAndSetCookie = (userId , res)=>{
    const token = jwt.sign({userId} , process.env.JWT_SECRET , {
        expiresIn : '15d', 
    } )
    res.cookie("jwt" , token , {
        httpOnly: false,
        secure: true,
        sameSite:'none'
    })
}

CORS Code :

app.use(cors({credentials : true , origin : 'http://localhost:3000'}));

Frontend Code for sending POST request for Login :

const handleSubmit = async (e) => {
        e.preventDefault();
        // console.log(formData);
        if (!formData.password || !formData.username) {
            toast("Please Fill All the Fields !");
            return;
        }

        try {
            setLoading(true);
            const res = await fetch(`${PROXY_URL}/api/auth/login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(formData),
            });
    
            const data = await res.json();
            if (!res.ok){
                toast.error(data.error || "Failed to Login");
                setLoading(false);
                return;
            }
            setLoading(false);
            setIsError(false);
            // console.log(data);
            console.log(document.cookie);
            toast.success("User Logged In Successfully !");
            setFormData({
                username: "",
                password: "",
            })
        } catch (error) {
            setIsError(true);
            console.log(error);
        }
    };

Network Tab Picture :

Network tab pic

Application tab Picture at same time:

application Tab pic

What to do ?


Solution

  • This very often happens to me as well. Can you try to rewrite your api call to have credentials set to include.

              const res = await fetch(`${PROXY_URL}/api/auth/login`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(formData),
                    credentials: 'include'
                });
    

    I also think you might need to adjust the server to this:

        res.cookie("jwt" , token , {
            httpOnly: true, 
            // I think if server needs to set a cookie it must be httpOnly
            secure: process.env.NODE_ENV === 'production', 
            sameSite:'none'
        })
    

    In addition these two posts might help you: