0

I am sending 3 cookies form backend which is hosted

2 are httpOnly and 1 is normal one , but that normal one (logged_in) cookie is not accessible from react-cookie.

On console log cookies is coming undefined.

FRONTEND CODE:

import { useCookies } from "react-cookie";
import { useSelector } from "react-redux";
import { getUser } from "../../features/user/UserSlice";
import { useGetMeQuery } from "../../services/api/UserApi";
import FullScreenLoader from "../FullScreenLoader/FullScreenLoader";
// import { userApi } from '../../redux/api/Userapi';

const RequireUser = ({ children }) => {
  const { isFetching, isLoading } = useGetMeQuery();
  const [cookies] = useCookies(["logged_in"]);
  const user = useSelector(getUser)?.data;

  console.log(cookies); //This is coming undefined

  if (isLoading || isFetching) {
    // Loading state, show loader
    return <FullScreenLoader />;
  }


//i want to check if(user && cookies.logged_in)

  if (user) {
    // User is already logged in
    return children;
  } else return null;
};

export default RequireUser;

BACKEND CODE:

// Cookie options
const accessTokenCookieOptions = {
  expires: new Date(
    Date.now() + config.get("accessTokenExpiresIn") * 60 * 1000
  ),
  maxAge: config.get("accessTokenExpiresIn") * 60 * 1000,
  httpOnly: true,
  sameSite: "none",
};

const refreshTokenCookieOptions = {
  expires: new Date(
    Date.now() + config.get("refreshTokenExpiresIn") * 60 * 1000
  ),
  maxAge: config.get("refreshTokenExpiresIn") * 60 * 1000,
  httpOnly: true,
  sameSite: "none",
};

// Only set secure to true in production
if (process.env.NODE_ENV === "production") {
  accessTokenCookieOptions.secure = true;
  refreshTokenCookieOptions.secure = true;
}


    res.cookie("access_token", access_token, accessTokenCookieOptions);
    res.cookie("refresh_token", refresh_token, refreshTokenCookieOptions);
    res.cookie("logged_in", true, {
      ...accessTokenCookieOptions,
      httpOnly: false,
      secure: false,
      path: "/",
    });

Am i missing something , any type of help will be useful.

aditya rawat
  • 35
  • 2
  • 5

0 Answers0