Axios is not sending the cookie to my backend API even when setting the withCredentials properly.
Front-end (NextJS):
import axios from "axios"
const BASE_URL = "http://localhost:8000"
export default axios.create({
baseURL: BASE_URL,
headers: { "Content-Type": "application/json" },
withCredentials: true,
})
Front-end Login (NextJS - Next Auth)
async authorize(credentials, req) {
const res = await axios.post(
"auth/signin",
{
email: credentials?.email,
password: credentials?.password,
}
)
console.log(res.headers)
const user = await res.data
if (user) {
return user
} else {
return null
}
},
In the above code, when I use consloe.log
to read the headers, I can clearly see that I am getting the cookie from the backend correctly:
AxiosHeaders {
'x-powered-by': 'Express',
'access-control-allow-origin': 'http://localhost:3000',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'set-cookie': [
'site-auth.session-token=j%3A%7B%22accessToken%22%3A%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzaTNqc255cm50djdwMTRmenljY2UybWQiLCJlf_KU2ygyjCp096shZCXL_kQfR1U3LdYLSbPQ5VTSo%22%2C%22tokenId%22%3A%22clksubs1x00008z8nmospe1yk%22%7D; Domain=localhost; Path=/; Expires=Tue, 08 Aug 2023 21:58:03 GMT; HttpOnly; Secure; SameSite=None'
],
'content-type': 'application/json; charset=utf-8',
'content-length': '175',
etag: 'W/"af-sE/2jElZ1eZqOhODKrhXa4Tz3xw"',
date: 'Tue, 01 Aug 2023 21:58:03 GMT',
connection: 'close'
}
But when I try to test and get the User Profile, I am getting an error from Axios indicating that the API has rejected the request. When I checked the API logs, I can see that the cookie is not being passed to it.
Front-end Axios Calling the Profile End-point:
const getProfile = async () => {
const res = await axios.get("/user/profile")
setProfile(res.data)
}
However, I noticed something important. My API is getting other cookies from Next-Auth, which means that Axios is in fact is sending cookies, but not the one I created.
Also, I can see the list of cookies in the browser (Chrome) console, but not the cookie I created
For some reason, it seems that my cookie is not being saved or Axios is not saving it or sending it.
I have tested my API using Postman and everything is fine and I can see the cookie being generated and used properly by Postman.
Here are some more information about the backend API (NestJS)
Back-end API (NestJS)
app.enableCors({
origin: 'http://localhost:3000',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
credentials: true,
optionsSuccessStatus: 204,
});
Back-end Generating Cookie (NestJS)
res.cookie(
'site-auth.session-token',
{
accessToken,
refreshToken,
tokenId,
},
{
httpOnly: true,
sameSite: 'none',
domain: 'localhost',
secure: true,
expires: this.getRefreshExpiry(),
},
);
Please help. I have been stuck for hours and I am unable to proceed with my app. I googled a lot but not hope.