1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The property withCredentials can help you, its work with axios and send the cookie

const instance = axios.create({
   withCredentials: true,
   baseURL: BASE_URL
})
instance.get('/todos')

see the doc and this topic topic

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.