Cookie not setting in the browser but workers in postman (Express js)

37 Views Asked by At

am sending the cookie from the backend API (http only cookie ). when I sent the request using postman the cookie setts in the header (Set-Cookie) but when I try sending the request from frontend using redux the cookie don't appear in the browser cookies
browser image

Postman image

respond header have the cookie image of the respond header

userController.js

// Public
// /users/login GET
// auth user
const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    res.status(403);
    throw new Error("email or password empty");
  }
  const user = await User.findOne({ email });
  if (!user) {
    res.status(404);
    throw new Error("user not found");
  }

  if (bcrypt.compareSync(password, user.password)) {

    //generate jwt token and send it  
    genToken(res, user._id);


    res.status(200).json({
      message: "User logged in",
      user: {
        id: user._id,
        name: user.name,
        email: user.email,
      },
    });
  } else {
    res.status(401);
    throw new Error("email or password not correct");
  }
});

genToken.js

const genToken = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "30d",
  });

  // set jwt hhtp cookie on the server
  res.cookie("jwt", token, {
    httpOnly: true,
    secure: false, //////////////// development only
    sameSite: "strict",
    maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days,
  });
};

**redux endpoint for /auth **

    login: builder.mutation({
      query: (data) => ({
        url: `${USERS_URL}/auth`,  // USER_URL=/users
        method: "POST",
        body: data,
      }),
    }),

i disabled CORE for the browser using an extencion moesif

and installed "cors" package

server.js

import express from "express";
import cors from "cors";


const app = express();

var corsOptions = {
  origin: "*",
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204,
  credentials: true,
};
app.use(cors(corsOptions));


but didn't work

1

There are 1 best solutions below

0
Rabah Abellache On

i managed to get it work .

first set the origin to "http://localhost:5173" and set credentials to "include" in the redux query and set sameSite to "lax" in the token options and disable the extinction