2023-12-12

Cookies are sent on localhost but when deployed on vercel the cookies are not sent

I've created a MERN project wherein I'm sending a jwt token in cookies after user's successfull authentication which works fine on localhost and I can make add, remove, fetch API calls which has verifyUser middleware.When I've deployed the frontend and backend on vercel there is some issue I don't know what exactly but the cookies are not sent.

//login controller

const loginUser = async (req, res) => {
  const { email, password } = req.body
  try {
    // Validators
    if (!email || !password) {
      return res.status(400).json({ Error: "Missing fields!" })
    }

    // Check for existing users with the same email
    const user = await User.findOne({ email })
    if (!user) {
      return res.status(400).json({ Error: "Invalid email address" })
    }

    const comparePassword = await bcrypt.compare(password, user.password)
    if (!comparePassword) {
      return res.status(401).json({ Error: "Incorrect Password!" })
    }

    const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET_KEY, {
      expiresIn: "24h",
    })

    const { password: userPassword, ...others } = user._doc

    res
      .cookie("access_token", token, {
        httpOnly: true,
        maxAge: 86400000,
        sameSite: "none",
      })
      .status(200)
      .json({ ...others })
  } catch (error) {
    return res.status(500).json(error.message)
  }
}

//verifyUser middleware

const verfiyToken = (req, res, next) => {
  const token = req.cookies.access_token
  if (!token)
    return res.status(401).json({ Error: "You are not authenticated" })

  jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {
    if (err) return res.status(403).json({ Error: "Token is not valid" })
    req.user = user
    next()
  })
}

//cors middleware

//Middleware
const corsOptions = {
  origin: process.env.CLIENT_URL,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true,
  // exposedHeaders: ["set-cookie"],
}

app.use(cors(corsOptions))

//vercel configuration file

{
  "version": 2,
  "builds": [
    {
      "src": "index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}

I'm stuck on this since last 2-3 days. I've tried searching for similare problems and also checked the vercel docs, didn't find the exact answer. I don't know if it is related to vercel configuration file, cors or any other issues. I'm happy to provide more code snippet if required.

I've added this images please do check.

// localhost response images

localhost network tab cookies image

localhost response headers image

localhost application tab->cookies image

// production response images

production network tab cookies image

production response headers image

production application tab->cookies image



No comments:

Post a Comment