I would like to add csurf as an express middleware inside the react-server for a universal app.
What I want to achieve is adding the csrf token to a hidden input in a form in the react component to maintain the same csrf protection flow a server-rendered website would provide, but within a SPA.
Is this technically possible within the react-server? If so, how can I pass the csrf token that is available in the response object to the react component via the page (ideally)?
Let's say you have a NodeJS and Express back end that interacts with your React client. You can install a library called csurf that's used to generate CSRF tokens, and you can send them to your client through an endpoint. Now you need to add the following endpoint.
Csurf module in Node.js prevents the Cross-Site Request Forgery (CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token.
The csurf function takes an optional options object that may contain any of the following keys: Determines if the token secret for the user should be stored in a cookie or in req.session. Storing the token secret in a cookie implements the double submit cookie pattern .
I'm using Axios in this example, but you can also use Fetch API to send valid headers with the X-CSRF-Token attached to the request. Let's say your minimal profile page component in React looks like this. You can then call the getCSRFToken function inside the useEffect as shown:
I actually ran into the same problem and luckily happened to come across the solution here: https://github.com/kriasoft/react-starter-kit/issues/1142
to use it just do:
app.use(csrf({ cookie: true, value: (req) => (req.cookies.csrfToken) }));
and then for every get request set a cookie with the csrf token:
res.cookie('csrfToken', req.csrfToken ? req.csrfToken() : null, { sameSite: true, httpOnly: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With