I’m building React app and making requests to my backend server with axios. On the server side I’m sending a response with cookie but on the client side there is no "Set-Cookie" header in response.
I configured axios to use credentials:
import axios from "axios";
export const API_URL = "http://127.0.0.1:8080/api";
const api = axios.create({
withCredentials: true,
baseURL: API_URL
});
export default api;
And configured express app to use CORS with proper options on the backend:
...
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true
}
app.use(express.json());
app.use(cookieParser());
app.use(cors(corsOptions));
...
Here is a Log in function on the server:
async logIn(req: Request, res: Response, next: NextFunction) {
try {
const { email, password } = req.body;
const user_data = await userService.logIn(email, password);
res.cookie('refresh_token', user_data.refresh_token, { maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true })
res.status(200).json({ message: 'Logged in successfully', ...user_data });
} catch (err) {
next(err)
}
}
And here is request from the client:
async logIn(email: string, password: string): Promise<void> {
try {
const response = await AuthService.logIn(email, password);
console.log(response.headers["set-cookie"]); // undefined
localStorage.setItem("_access_token", response.data.access_token);
this.setAuth(true);
this.setUser(response.data.user_dto);
} catch (err) {
console.log(err);
}
}
When I’m testing the log in endpoint with Postman everything is alright and I can see the cookie:
3
Answers
Finally solved the problem. Just opened React app on
127.0.0.1:3000
instead oflocalhost:3000
and set the same url to the "origin" in CORS options, than cookie was successfully saved in the browser.You can extract cookie(s) from an incoming request as such (
req.cookies
):Docs http://expressjs.com/en/resources/middleware/cookie-parser.html
accordance with the Fetch standard, client code cannot read Set-Cookie response headers, even if the server happens to be configured for CORS and lists Set-Header in its responses
Access-Control-Expose-Headers
header.