I'm actively trying to gain knowledge on httpOnly
cookie and found out lots of article on it that why should we use it.
But I haven't seen any practical example of how to work with it. From few trial and error, I came to knew that we can't set httpOnly
flag in browser and needed to be done on server. So I, used cookie-parser
library accordingly:
const express = require('express');
var cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.post('/generateToken', (req, res) => {
res.cookie('AccessToken', JWT_AUTH_TOKEN, {
expires: new Date(new Date().getTime() + 30 * 1000),
sameSite: 'strict',
httpOnly: true,
})
res.cookie('RefreshToken', JWT_REFRESH_TOKEN, {
expires: new Date(new Date().getTime() + 31557600000),
sameSite: 'strict',
httpOnly: true,
}).send("hello")
});
app.listen(process.env.PORT || 5050);
By this I successfully get the cookie stored in my browser with all the property like sameSite
, HttpOnly
except secure:true
as I'm on local host. But the problem is as we cant access these httpOnly
token with javascript, How do I send it to particular routes with proper header like below
let token = req.headers['authorization'];
and send httpOnly cookie refreshToken
to lets say /refresh
Route to get new accessTokens
with Axios or whats the way of doing it?
When you have set the cookies with HttpOnly flag, the cookies will be automatically sent via HTTP request from the browser to the server. You don't have to explicitly set it in HTTP Header.
With cors
installed at the server, you can access the cookie with req.cookies
.
I am not sure with axios, but if using fetch API, we will need to add credential:'include'
option in the fetch API, so that the HttpOnly cookies can be set.
Take a look at this post.