cookie is not being set with different frontend and backend domain

Viewed 20

i deployed my react app in netlify and my node js app in heroku after that setting cookies are not working after facing this problem i deployed both my frontend and backend in Heroku and it is now working but this method doesn't scale well for my frontend i can't make automatic deploy from my GitHub repo whenever i push new changes

so how can work with cookies having different backend and frontend domain

currently i deployed the backend on Heroku and the frontend in Netlify, and everything works except for the cookies.

and the server is sending the cookies properly in the login request but the browser doesn't save it to the cookies storage

index.js

const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");
const authRoute = require("./routes/auth-route.js");

app.set("trust proxy",1);
/* A middleware that allows cross-origin requests. */
app.use(
  cors({
    credentials: true,
    origin: "https://myfrontend.com",
  })
);

/* Parsing the cookies in the request object. */
app.use(cookieParser({}));

/* A middleware that parses the request body and makes it available in the request object. */
app.use(express.json());

//api routes
/* A middleware that is used to route the requests to the authRoute.js file. */
app.use("/api/auth", authRoute);  

authRoute.js

const router = require("express").Router();
const {login} = require("../controllers/auth-controller");
router.post("/login", login);
module.exports = router;

auth-controller.js

const bcrypt = require("bcrypt");
const User = require("../models/User");
const generateJwt = require("../utils/generateJWT");
const login = async (req, res) => {
    try {
      /* Finding a user in the database with the email that was sent in the request body. */
      const user = await User.findOne({ email: req.body.email });
      /* This is checking if the user exists in the database. If the user does not exist, it will return
            a 404 status code and a message. */
      if (!user)
        return res.status(404).json({ success: false, message: "Email or Password Incorrect" });
    
      /* Comparing the password that was sent in the request body to the password that is stored in the
        database. */
      const validatePassword = await bcrypt.compare(req.body.password, user.password);
  
      /* This is checking if the password that was sent in the request body matches the password that is
         stored in the database. If the password does not match, it will return a 404 status code and a
         message. */
      if (!validatePassword)
        return res.status(404).json({ success: false, message: "Email or Password Incorrect" });
  
      /* Destructuring the user object and removing the password from the object. */
      const { password, ...others } = user._doc;
      /* Generating a JWT token. */
      const token = generateJwt(user._id);
  
      /* Setting a cookie on the client side. */
      //if rememberMe is checked in the client the cookie will last for 30 day if not only for session
      if (req.body.rememberMe === true) {
        res.cookie("isLogged", true, {
          sameSite: "none",
          secure: true,
          domain: "app-frontend.netlify.app",
          maxAge: 2592000000, //30 day = 2,592,000,000 msg
        });
  
        res.cookie("authToken", token, {
          httpOnly: true,
          sameSite: "none",
          domain: "app-frontend.netlify.app",
          secure: true,
          maxAge: 2592000000, //30 day = 2,592,000,000 msg
        });
      } else {
        res.cookie("isLogged", true, {
          sameSite: "none",
          domain: "app-frontend.netlify.app",
          secure: true,
        });
  
        res.cookie("authToken", token, {
          httpOnly: true,
          sameSite: "none",
          domain: "app-frontend.netlify.app",
          secure: true,
        });
      }
      res.status(200).json({ success: true, user: others });
    } catch (err) {
      console.log(err);
      res.status(500).json({ success: false, message: err });
    }
  };

  module.exports = {login };

frontend side axiosConfig.js

import axios from "axios";
const axiosInstance = axios.create({
  withCredentials: true,
  baseURL: "https://app-backend.herokuapp.com/api/",
});

export default axiosInstance;

login function

  import axios from "../../utils/axiosConfig";
  const login = async () => {
    try {
      dispatch(setIsLoading(true));
      const data = {
        email: email.current.value,
        password: password.current.value,
        rememberMe: rememberMe.current.checked,
      };
      const res = await axios.post("auth/login", data);
      dispatch(setIsLoading(false));
      if (res.status === 200) {
        dispatch(setUser(res.data.user));
      }
    } catch (err) {
        dispatch(
          setIsError({
            status: true,
            message: err.response.data.message,
          })
        );
        dispatch(setIsLoading(false));   
    }
  };
0 Answers
Related