I use React Single Page Application as a client side or Create React App (CRA).
In my backend i use Node.js & Express.
to fetch data or store i need to call API from client to backend.
actually I've seen there are several middleware like: - Express CSURF
but to be honest I don't understand how to send a CSRF token to the client every request. I have tried several times, by inserting the CSRF into a cookie and then taking it on the client side. but when the first request or new cookie is stored, I get error Invalid CSRF Token
.
and even though I did this:
app.use(session({
genid: function (req) {
return uuidv4() // use UUIDs for session IDs
},
name:keys.session.name,
secret: keys.session.secret,
resave: false,
saveUninitialized: true,
rolling:true,
cookie: {
secure: false,
httpOnly: true,
maxAge:keys.session.maxAge, // satu hari,
sameSite:true,
}
}));
app.use(passport.session());
app.use(cookieParser());
app.use(csrf({ cookie: false }));
app.use((req,res,next)=>{
res.cookie('CSRF_token', req.csrfToken(), { sameSite: true });
})
Which means the CSRF_token cookie will change each request. but I only set it once like this : axios.defaults.headers.common['csrf-token'] = csrf;
and the results its still work, which should not working.
So do I need CSRF? or how to configure the correct one on react SPA.