I have seen across all blogs and articles is that there is two ways to handle JWTtokens
, put them inside localStorage
which subjected for XSS
attack or put them inside Cookies
and set httpOnly
and secure
flags to avoid XSS
.
Using localStorage
For every request to the server you extract the token
out of the localStorage
and append it to Authorization : Bearer <Token>
manually.
Using Cookies
It is handled server side since it won't be accessed by JS
client side, what you do is res.cookies(token)
, and it is going to be sent automatically for every subsequent call unlike localStorage
But lately i saw some developers simply put the token in the headers using res.headers('x-auth', token)
.
- Is it a third way to handle JWT?
- Would the X-Auth header set for every subsequent request to the server like cookies automatically or you have to set it manually (like in case of localStorage) ?
- Are tokens in X-Auth header cannot be accessed by JS and secure like cookies?
- what is the difference between doing it your way res.header('X-auth') and res.cookie(token) ?
Finally what is the best way to do it if my API is consumed by by ReactJS web app and react-native mobile application?
Thanks