Home > Back-end >  Cookies sent from backend but not set correctly on frontend
Cookies sent from backend but not set correctly on frontend

Time:02-10

I'm running into this issue:

  • localhost:3000 (React App)
  • localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;
    
    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};

If anyone could guide me on what to do I'd be grateful

UPDATE: I did some testing and the results were as follows: when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const 

});

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

CodePudding user response:

Here's a helpful link for understanding httpOnly cookies and alternate methods. How to get HTTP-only cookie in React?

CodePudding user response:

I was able to solve the issue by doing those steps:

  1. Making sure the fetch request has the withCredntials: true and credentials: 'include', so the fetch request would be like this:
    fetch("http://localhost:9000/testAPI", {
                withCredntials: true,
                credentials: 'include'
    })

Keep in mind this is only working with GET requests not POST requests without the 2nd step.

  1. For POST requests being blocked by cors, just make sure you have this line in your backend after you've required cors of course app.use(cors({credentials: true, origin: true})); using * or http://localhost:3000 (regardless of port number) instead of true seems to give the error.

NOTE: According to @ikhvjs the withCredntials: true is not required, however I'm yet to try this so try at your own risk.

Thank you all for the help :D

  • Related