How to set cookies at client side from the server response using express.js?

16 Views Asked by At

I am using express 4.18, express-session 1.18. Intends to set cookies at the client side (i.e. browser) via using a login controller(following code). In between, i am also using a middleware before reaching the login controller. The middleware is just checking whether the username and email are valid or not.
Not getting success in setting cookies in the browser, tried so many times.
At client side i am using react where i am just calling login api with credentials(email, username); nothing much in the code there.

exports.loginUser = async (req, res) => {
  const { email, username } = req.userData;
  try {
    const accessToken = jwt.sign({ email, username }, JWT_SECRET, { expiresIn: "1h" });
    const refreshToken = jwt.sign({ email, username }, JWT_SECRET, { expiresIn: "1d" });

    req.session.email = email;
    req.session.username = username;

    res.cookie("accessToken", accessToken);
    res.cookie("refreshToken", refreshToken);
    res.cookie('isAuthenticated', true);
    res.cookie("email", email);
    res.cookie("username", username);
    res.cookie("sessionId", req.session.id);
    res.cookie("sessionExpires", req.session.cookie.expires);

    res.status(200).json({ message: "You are successfully logged in" });
  } catch (error) {
    console.error("Error logging in user:", error);
    res.status(500).json({ message: "Internal server error" });
  }
};

Following snippet of code is from app.js(the main file) of expressjs

app.use(session({
  secret: process.env.SESSION_SECRET, 
  resave: false,
  saveUninitialized: true,
  store: store, 
  cookie: {
    maxAge: 24 * 60 * 60 * 1000 
  }
}));

One more thing, Things are working fine using postman. There i can see cookies.

Please Help!

0

There are 0 best solutions below