Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can not send cookie back from client, tried many ways #4907

Open
namnguyen2091 opened this issue Aug 9, 2022 · 24 comments
Open

Can not send cookie back from client, tried many ways #4907

namnguyen2091 opened this issue Aug 9, 2022 · 24 comments

Comments

@namnguyen2091
Copy link

Summary

I'm new user from nodejs (expressjs) and axios too and I have a problem. I set cookie from nodejs server with:

app.use(cors({
	origin: 'http://localhost:2000'
	credentials: true
}));
res.cookie('refresh_token', refresh_token, {
      maxAge: 30 * 24 * 60 * 60 * 1000,
      httpOnly: true,
      sameSite: 'strict'
});

I can see response cookie from browser but in storage I can not see. I use res.header do the same, nothing happen. httpOnly: false does not work.
And in client I try:

const instance = axios.create({
	withCredentials: true,
	baseURL: 'http://127.0.0.1:5000',
	headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'},
	credentials: 'include',
})
instance.post(
	'/users/def/refresh_token', 
	{"access_token":"ABC"}
)

I can not find other ways to do this, every result I got in google do this but I dont know why that not working for me. With Postman it automatic send cookie every request. Please help me!

Environment

  • API: http://localhost:5000
  • Front end: http://localhost:2000
  • Axios Version: 0.27.2
  • Browser: Chrome 101.0.4951.64 (Official Build) (64-bit)
  • Node.js Version: v12.13.0
  • OS: Ubuntu 20.4
  • Additional Library Versions: Reactjs 17.0.2
@js-writer
Copy link

js-writer commented Aug 20, 2022

Yes, it is not working.
Cookie is set but value is empty...

[Edit]:
Ok it is working.
In my case I forgot to add "withCredentials: true" also to login request. After that everything started to work.

@mohabisback
Copy link

thanks, you helped alot

@mohabisback
Copy link

both of you helped, thank you both

@Muralidhar22
Copy link

Muralidhar22 commented Oct 29, 2022

Yes, it is not working. Cookie is set but value is empty...

[Edit]: Ok it is working. In my case I forgot to add "withCredentials: true" also to login request. After that everything started to work.

thanks for this it worked, i missed to add credentials: 'include' in my login fetch request

@noahreeves-1
Copy link

IT WORKED! Why did it take me so long to find this?!!

@Abhiie
Copy link

Abhiie commented Apr 7, 2023

// middlewares
app.use(cors());
app.use(cookieParser());
app.use(express.json());

this is servers.js file.

const googleAuth = async (req, res, next) => {
const { name, email, img } = req.body;
try {
// check if user exists or not
const user = await User.findOne({ email });

if (user) {
  const token = generateToken(user._id);

  res.cookie("access_token", token).status(200).json({
    success: true,
    user,
  });
} else {
  // Create new user from Google Provider
  const newUserFromGoogle = await User.create({
    name,
    email,
    img,
    fromGoogle: true,
  });
  const token = generateToken(newUserFromGoogle._id);

  res.cookie("access_token", token).status(200).json({
    success: true,
    user: newUserFromGoogle,
  });
}

} catch (error) {
console.log(error);
res.status(400);
return next(error);
}
};

module.exports = {
loginUser,
signupUser,
googleAuth,
};
above code is from auth.js file //controllers
const jwt = require("jsonwebtoken");

const protect = async (req, res, next) => {
try {
// Get token from header
const token = req.cookies.access_token;

if (!token) {
  res.status(401);
  return next(new Error("Not authorized, no token"));
}

// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// Get user id from token and assign to req
req.user = { _id: decoded._id };
next();

} catch (error) {
res.status(401);
return next(new Error("Not authorized"));
}
};

module.exports = protect;
above code is from auth.js //middlewares
but still i am not able to set cookies help me

@Abhiie Abhiie mentioned this issue Apr 7, 2023
@destineefelix
Copy link

Mine works fine in development stage but does not set cookie in production.
Any solution to this.

@willyanbertolino
Copy link

In production I got the same issue. The cookie was not set by the browser, I tryed a lot of possible solutions but what solve my problem was change the domain name. I deployed my API as server.mydomain.com and my frontend was anotherdomain.app and CORS was properly configured. I was able to send request to 'open' routes, but when I tried to login the cookie was ignored by the browser. So, when I changed the frontend to mydomain.com the cookie was set perfectly.

@Aryan-Jagadale
Copy link

@willyanbertolino Thanks for your solution. It took me whole day to figure out, but the change in domain name solved my problem. Thank you so much.

@oyatadaniel
Copy link

Tried everything but still not working any help`app.post("/api/auth/login", cors(corsOptions), (req, res) => {
const { email, password } = req.body;
res.cookie("sky", "blue");
const q = "select * from users where email = ?";
db.query(q, email, (err, data) => {
if (err) {
res.send({ err: err });
}
if (data.length > 0) {
bcrypt.compare(password, data[0].password, (error, result) => {
if (result) {
const name = data[0].name;
const role = data[0].role;
const email = data[0].email;
const store_id = data[0].store_id;
const token = jwt.sign(
{ name, role, email, store_id },
process.env.TOKEN,
{
expiresIn: 300,
}
);

      res.cookie("token", token).send({ Status: "Success", token, data });
      console.log(token);
    } else {
      return res.json({ message: "Incorrect Login Credentials" });
    }
  });
} else {
  return res.json({
    message: "You Don't Look Familiar to our System, Contact IT Admin",
  });
}

});
});`

@Aryan-Jagadale
Copy link

You hadn't provided cookie options in cookie method. Refer following blog.

@Gaurav200247
Copy link

In production I got the same issue. The cookie was not set by the browser, I tryed a lot of possible solutions but what solve my problem was change the domain name. I deployed my API as server.mydomain.com and my frontend was anotherdomain.app and CORS was properly configured. I was able to send request to 'open' routes, but when I tried to login the cookie was ignored by the browser. So, when I changed the frontend to mydomain.com the cookie was set perfectly.

Help Plz,
Can you tell me what changes you do in domain because I am using vercel
and my client domain is => https://video-streamer-app-frontend.vercel.app
and my server domain is => https://video-streamer-app.vercel.app

in localhost its storing cookies in browser but in deployment it do not
I am also using cors with withcredentials and origin at server side
app.use(
cors({
origin: "https://video-streamer-app-frontend.vercel.app",
credentials: true,
})
);

and also using
axios.defaults.withCredentials = true;
at client side

plz help!!!

@willyanbertolino
Copy link

willyanbertolino commented Jul 19, 2023 via email

@Gaurav200247
Copy link

In production I got the same issue. The cookie was not set by the browser, I tryed a lot of possible solutions but what solve my problem was change the domain name. I deployed my API as server.mydomain.com and my frontend was anotherdomain.app and CORS was properly configured. I was able to send request to 'open' routes, but when I tried to login the cookie was ignored by the browser. So, when I changed the frontend to mydomain.com the cookie was set perfectly.

Help Plz, Can you tell me what changes you do in domain because I am using vercel and my client domain is => https://video-streamer-app-frontend.vercel.app and my server domain is => https://video-streamer-app.vercel.app

in localhost its storing cookies in browser but in deployment it do not I am also using cors with withcredentials and origin at server side app.use( cors({ origin: "https://video-streamer-app-frontend.vercel.app", credentials: true, }) );

and also using axios.defaults.withCredentials = true; at client side

plz help!!!

It did'nt do anything bro.
Is there any other way?

@anuj615
Copy link

anuj615 commented Aug 10, 2023

I am also having same issue. Cookie works in development but not in production. My frontend is deployed on like domain.com and backend on cloud.cyclic.app

@anuragchauhan766
Copy link

@Gaurav200247 did you try setting same-site: "none" in cookie?
eg.

res.cookie("refreshtoken", refreshToken, {
      httpOnly: true,
      sameSite: "none",
      secure: true,
      // maxAge: 24 * 60 * 60 * 1000, // 1 day
      maxAge: 3 * 60 * 1000,

      path: "/api/auth/refresh",
    });

i just implemented a full stack auth in which server and client are on different domains so setting sameSite: "strict" will stop cookie at client side because of different domain.

and cors settings are like this

app.use(
  cors({
    origin: ["http://localhost:5173", process.env.CLIENT_BASE_URL as string],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true,
  })
);

@Gaurav200247
Copy link

@Gaurav200247 did you try setting same-site: "none" in cookie? eg.

res.cookie("refreshtoken", refreshToken, {
      httpOnly: true,
      sameSite: "none",
      secure: true,
      // maxAge: 24 * 60 * 60 * 1000, // 1 day
      maxAge: 3 * 60 * 1000,

      path: "/api/auth/refresh",
    });

i just implemented a full stack auth in which server and client are on different domains so setting sameSite: "strict" will stop cookie at client side because of different domain.

and cors settings are like this

app.use(
  cors({
    origin: ["http://localhost:5173", process.env.CLIENT_BASE_URL as string],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true,
  })
);

I have tried what you are saying my cookie config are :
const options = {
maxAge: new Date(
Date.now() + process.env.COOKIE_LIFETIME * 24 * 60 * 60 * 1000
),
httpOnly: true,
secure: true,
sameSite: "none",
path: "/",
}

and using cors as :
app.use(
cors({
origin: "https://video-streamer-app-frontend.vercel.app",
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
credentials: true,
})
);

in production app works fine cookie is saving but in deployment no cookie is saved I tried logging response headers and got this :

Response Headers: {cache-control: 'public, max-age=0, must-revalidate', content-type: 'application/json; charset=utf-8'}
cache-control
:
"public, max-age=0, must-revalidate"
content-type
:
"application/json; charset=utf-8"

i am getting max Age = 0;

can someone help.

@Paulzodak
Copy link

@Gaurav200247 did you try setting same-site: "none" in cookie? eg.

res.cookie("refreshtoken", refreshToken, {
      httpOnly: true,
      sameSite: "none",
      secure: true,
      // maxAge: 24 * 60 * 60 * 1000, // 1 day
      maxAge: 3 * 60 * 1000,

      path: "/api/auth/refresh",
    });

i just implemented a full stack auth in which server and client are on different domains so setting sameSite: "strict" will stop cookie at client side because of different domain.

and cors settings are like this

app.use(
  cors({
    origin: ["http://localhost:5173", process.env.CLIENT_BASE_URL as string],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true,
  })
);

using sameSite:"none" fixed my issue, Thanks.

@rossanag
Copy link

rossanag commented Nov 2, 2023

Hello, I am facing the same issue, I've tryed everything. My server is at localhost.

Server

const app = express();

app.use(cookieParser());
app.use(cors(corsOptions)); 
app.use(credentials)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Just in case, I set the corsOptions

const allowedOrigins = [
    'https://www.yoursite.com',
    'http://127.0.0.1:5173',
    'http://localhost:5173',    
    'http://127.0.0.1:3000',
    'http://localhost:3000',
    'http://localhost:3000'
];


const corsOptions = {
    origin: (origin, callback) => {
        if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
            callback(null, true)
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    },
    methods: "GET,POST,PUT,DELETE,OPTIONS",
    credentials:true,         
    optionsSuccessStatus: 200
}

Then I set the cookie when a new user is created:

res.cookie('refreshToken', tokens.refresh_token, {                    
                    secure:  process.env.NODE_ENV === 'production', // true - Requires HTTPS
                    httpOnly: true, // Cookie cannot be accessed by JavaScript
                    sameSite: 'None',
                    maxAge: tokenInfo.expiry_date * 1000,
                });
                
                res.status(201).json(user);                   

process.env.NODE_ENV=development

Client

The axios instance, set credentials to True.

export const apiGoogle = axios.create({
	baseURL:  import.meta.env.VITE_SERVER_ENDPOINT,
	timeout: 6000,	
	headers: { Accept: 'application/json' },
	withCredentials: true,
});

However, set cookies is empty in the devTools, and in the server side, req.cookies is empty. Any hint it's apprecieted, thanks.
Best!

Node : 18.18.0
OS: Ubuntu 22.04

@360Parminder
Copy link

my is not working

@amarnath-dev
Copy link

amarnath-dev commented Feb 18, 2024

Yes, it is not working. Cookie is set but value is empty...

[Edit]: Ok it is working. In my case I forgot to add "withCredentials: true" also to login request. After that everything started to work.

Thank you so much bro...I've spent 3 days because of this issue.
I think when you set the req.cookies() in the server code and user login time you have to include the "withCredentials: true" in the axios request.
Thank you once again❤️

@davidd74
Copy link

For anyone that's facing this problem, what worked for me was disabling the adblocker on my deployed website.

Here's the code I used for setting the cookies

res.cookie("token", token, { withCredentials: true, sameSite: "none", secure: true, httpOnly: true, });

@chapeee
Copy link

chapeee commented Feb 23, 2024

credentials: 'include'

what was the issue can you please help me out with the code sample

@inder231
Copy link

👋 Hey everyone,
I was also struggling with same issue, and now I found the answer, I hope this will fix your as well.

  • Server side

    • Use cors with following configuration
    • CORS config: app.use(cors({origin: <your_client_url> , withCredentials: true})
    • Sending cookie:
      res.send(<cookie_name>, <cookie_value>,
      { httpOnly: true, // true if don't want to access cookie via js on client side
      secure : true, // mandatory with sameSite:none property
      sameSite: "none", // mandatory to set if client and server are on different domains
      maxAge: <your_desired_cookie_expiry_time>,
      path: "/" // must set path "/" here
      })
  • Client side

    • Create axios instance
    • export const baseAPI = axios.create({
      baseURL: ${API_URL},
      withCredentials: true, // mandatory to set true
      });
  • I hope this will solve the issue, as it solved for me struggling for loooooooong time🎯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests