[MEAN] How to use httpOnly JWT with React and Node

Posted by Jarxi on 2020-11-29

How to use httpOnly JWT with React and Node

It is unsafe to store JWT in either localStorage or cookie, although many people do this.
HttpOnly cookie means frontend javascript is not able to read or write it. Thus we cannot generate httpOnly cookie through react. The workaround is to generate httpOnly cookie at backend and send it to the front end. After the JWT is send to frontend, every axios request send from fronend to backend should have cookies automatically attached.

Server Side code in Server.js Or Index.js

Setup Cors

1
2
3
4
5
app.use(
cors({
origin: 'http://localhost:3000', // origin should be where the frontend code is hosted
})
);

Setup Headers

1
2
3
4
5
6
7
8
9
app.use(function (req, res, next) {
res.header('Content-Type', 'application/json;charset=UTF-8');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});

Setup Cookie Parser

The cookie send through axios is in format token={token};somethingelse={somethingelse}. We need a cookie parser to parse it.
npm install cookie-parser
Add following code to server.js or index.js
app.use(cookieParser())
When you need to read the cookie, use req.cookies.token or req.cookies.somethingelse

Client side code

Ask axios to automatically add cookie to every request send from frontend to backend.
In the beginning of App.js, add axios.defaults.withCredentials = true

References

JWTs on frontend clients (GraphQL)



支付宝打赏 微信打赏

赞赏一下