kennydop
kennydop

Reputation: 1

Cookies won't set in browser but does in postman

I have searched around, but still can't get it to work. I followed this blog to set things up.

this is where I send my cookie (server):

//after user is has been authenticated
export const logInUser = async (req, res, next) => {
try {
  const token = getToken({ _id: req.user._id, username: req.user.username, email: req.user.email})
  const refreshToken = getRefreshToken({  _id: req.user._id, username: req.user.username, email: req.user.email})
  await User.findOne({ username: req.user.username}).then((user)=>{
      user.refreshToken.push({ refreshToken })
      user.save((error, user) => {
        if (error) {
          res.status(500).json(error)
        } else {
          //sending the cookie
          res.cookie("refreshToken", refreshToken, {httpOnly: true, secure: !dev, signed: true, maxAge: (60 * 60 * 24 * 30) * 1000, sameSite: "none"})
          res.send({ success: true, token,  _id: req.user._id, username: req.user.username, email: req.user.email})
        }
      })
    })
} catch (error) {
  next(error)
    res.status(500).json(error)
    console.log(error)
}
}

index.js (server):

const corsOptions ={
origin: true, 
credentials:true,
optionSuccessStatus:200
}
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cookieParser(process.env.COOKIE_SECRET))
app.use(cors(corsOptions));
app.use(passport.initialize());

making the request on the client-side (using next.js):

function login(username, password) {
axios.post("http://localhost:5000/api/auth/login", {username, password}, {withCredentials: true, credentials: 'include'}).then((res)=>{
  setCurrentUser(res.data)
}).catch((error)=>{
  console.log(error)
})
}

Response in browser

Everything works perfectly in postman

Upvotes: 0

Views: 2826

Answers (2)

kennydop
kennydop

Reputation: 1

I finally solved this by getting rid of the sameSite: "none" attribute on the cookie in this line res.cookie("refreshToken", refreshToken, {httpOnly: true, secure: !dev, signed: true, maxAge: (60 * 60 * 24 * 30) * 1000, sameSite: "none"})

Upvotes: 0

Khorne07
Khorne07

Reputation: 199

IF you are trying to see the cookie in your browser devtools then check this answer https://stackoverflow.com/a/38604501/16091749.

If what you are trying to do is to access your cookie from your Next app, then you can't do that unless you disable the httpOnly flag, which is not recommended in this case because you are keeping sensitive data in this cookie, so if you disable this flag your cookie will be vulnerable to any malicious script that may be in contact with it. For more info about the cookies check this link https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

Upvotes: 1

Related Questions