localstorage and cookies data not saving in browser in production

26 Views Asked by At

PS: It works perfectly fine in locally but it breaks in production!

I designed my login such that when it is successful, the user data will be saved in localstorage and httpOnly cookies will be stored in the browser. When I deployed locally to vercel, after logging in successfully the redirects kick in as the cookie data is not saved and the user data is not saved in the localstorage

This is my cookie settings in the NodeJS backend;

const generateToken = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "24h",
  });

  res.cookie("jwt", token, {
    httpOnly: true,
    secure: true,
    sameSite: "none",
    maxAge: 24 * 24 * 60 * 60 * 1000,
  });
};

This is my login controller in the backend

const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body;

  const user = await User.findOne({ email });

  if (user && (await user.matchPassword(password))) {
    generateToken(res, user._id);

    generateRefreshToken(res, user._id);

    res.status(201).json({
      _id: user._id,
      name: user.name,
      email: user.email,
      phoneNumber: user.phoneNumber,
    });
  } else {
    res.status(401);
    throw new Error("Invalid Email or Password");
  }
});

This is my login function in the frontend. I also used ReactToolkit with it.

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const res = await login(credentials).unwrap();

      dispatch(setCredentials({ ...res }));

      toast({
        title: "Login Successful",
        status: "success",
        duration: 3000,
        isClosable: true,
        position: "top",
      });

      navigate("/home");
    } catch (err) {
      toast({
        title: "Login Failed",
        variant: "subtle",
        description: err?.data.message || err.error,
        status: "error",
        duration: 5000,
        isClosable: true,
        position: "top",
      });
    }
  };

This is the setCredentials reducer function;

    setCredentials: (state, action) => {
      state.userInfo = action.payload;
      localStorage.setItem("userInfo", JSON.stringify(action.payload));
    },
0

There are 0 best solutions below