title: how to implement csurf on node js and react js?
body: <p>I have a react js application on node js, I can’t implement csurf on my application for a long time, how can I implement csurf in the right way?</p>
  <p><strong>project directory</strong></p>
  <pre><code>-admin
  -client
  -config
  -middleware
  ----file.js
  ----variables.js
  -models
  -node-modules
  -routes
  -utils
   index.js
   package-lock.json
   package.json
  </code></pre>
  <p><strong>main node js file</strong></p>
  <p><em>index.js</em></p>
  <pre><code>const express = require('express');
  const config = require('config');
  const path = require('path');
  const cookieParser = require('cookie-parser');
  const csrf = require('csurf');
  const mongoose = require('mongoose');
  const helmet = require('helmet');
  const compression = require('compression');
  const taskRoutes = require('./routes/task');
  const performerRoutes = require('./routes/performer');
  const categoryRoutes = require('./routes/category');
  const authRoutes = require('./routes/auth');
  const knowRoutes = require('./routes/know');
  const mobileRoutes = require('./routes/mobile');
  const statisticsRoutes = require('./routes/statistics');
  const businessRoutes = require('./routes/business');
  const fileMiddleware = require('./middleware/file');
  const varMiddleware = require('./middleware/variables');
  const bcrypt = require('bcrypt');
  const Admin = require('./models/admin');
  
  const app = express();
  
  const PORT = config.get('port') || 5000;
  
  app.use(express.json({ extended: true }));
  app.use(cookieParser());
  app.use(csrf({ cookie: {
      httpOnly: true,
      maxAge: 3600 // 1-hour
    }
  }));
  app.use(varMiddleware);
  app.use(fileMiddleware.fields([
      { name: 'avatar', maxCount: 1 },
      { name: 'photosWorks' },
      { name: 'icon', maxCount: 1 }
  ]));
  
  app.use(helmet());
  app.use(helmet.contentSecurityPolicy({
      directives: {
          defaultSrc: [&quot;'self'&quot;],
          scriptSrc: [&quot;'self'&quot;, &quot;'unsafe-inline'&quot;],
          styleSrc: [&quot;'self'&quot;, &quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css&quot;, 
          &quot;https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css&quot;, 
          &quot;https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css&quot;],
          fontSrc: [&quot;'self'&quot;, &quot;https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/fonts/&quot;],
          imgSrc: [&quot;'self'&quot;]
      }
  }));
  app.use(compression());
  
  app.use('/api/category/', categoryRoutes);
  app.use('/api/know/', knowRoutes);
  app.use('/api/new/task/', taskRoutes);
  app.use('/api/performers/', performerRoutes);
  app.use('/api/mobile/auth/', mobileRoutes);
  app.use('/api/admin/', authRoutes);
  app.use('/api/statistics/', statisticsRoutes);
  app.use('/api/business/', businessRoutes);
  
  if (process.env.NODE_ENV === 'production') {
      app.use('/', express.static(path.join(__dirname, 'client', 'build')));
      app.use('/', express.static(path.join(__dirname, 'admin', 'build')));
  
      app.get('/admin/*', (req, res) =&gt; {
          res.sendFile(path.resolve(__dirname, 'admin', 'build', 'index.html'))
      });
      app.get('*', (req, res) =&gt; {
          res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
      });
  }
  
  async function start() {
      try {
          await mongoose.connect(config.get('mongoUri'), {
              useNewUrlParser: true,
              useUnifiedTopology: true,
              useCreateIndex: true
          });
          const candidate = await Admin.findOne();
          if (!candidate) {
              const hashPassword = await bcrypt.hash('666666', 12);
              const admin = new Admin({
                  logAdmin: 'admin1234',
                  pasAdmin: hashPassword,
                  name: 'Sardor',
                  avatarUrl: '/images/cardImg2.jpg'
              });
              await admin.save();
          }
          app.listen(PORT, () =&gt; {
              console.log(`Server on port ${PORT}`);
          });
      } catch (e) {
          console.log(e);
      }
  }
  
  start();
  </code></pre>
  <p><em>variables.js</em></p>
  <pre><code>module.exports = function(req, res, next) {
      console.log('varMiddleware');
      res.cookie('XSRF-TOKEN', req.csrfToken());
      next();
  }
  </code></pre>
  <p><strong>this is a react component, in this component, how can I correctly implement csurf on the client side</strong></p>
  <p><em>for-business-page.js</em></p>
  <pre><code>import React, { Component } from 'react';
  import { Link, Redirect } from 'react-router-dom';
  import axios from 'axios';
  
  import './for-business-page.css';
  
  
  class ForBusinessPage extends Component {
  
      state = {
          name: '',
          phone: '',
          validBusiness: {},
          successBusiness: false
      }
  
      bidHendler = (e) =&gt; {
          e.preventDefault();
  
          const formData = new FormData(e.target);
  
          axios.post('/api/business/bid', formData)
              .then((response) =&gt; {
                  console.log(response);
                  this.setState({
                      name: '',
                      phone: '',
                      successBusiness: true
                  })
              })
              .catch((err) =&gt; {
                  const validBusiness = this.validHelper(err.response.data.errors);
                  this.setState({ validBusiness });
              })
      }
  
  
      validHelper = (arrErrors) =&gt; {
          let  validName = '', validPhone = '';
          
          for (let i = 0; i &lt; arrErrors.length; i++) {
              switch (arrErrors[i].param) {
                  case 'name':
                      validName = arrErrors[i].msg;
                      break;
                  case 'phone':
                      validPhone = arrErrors[i].msg;
                      break;
                  default:
                      continue;
              }
          }
  
          return {
              validName,
              validPhone
          };
      }
  
      inputControl = (e) =&gt; {
          switch (e.target.name) {
              case 'name':
                  this.setState({ name: e.target.value });
                  break;
              case 'phone':
                  this.setState({ phone: e.target.value });
                  break;
              default:
                  this.setState({ name: '', phone: '' });
          }
      }
  
      render() {
          const { name, phone, successBusiness } = this.state;
  
          if (successBusiness) {
              return &lt;Redirect to=&quot;/success&quot; /&gt;
          }
  
          return (
              &lt;div className=&quot;for-business-page&quot;&gt;
                  &lt;div className=&quot;container-fluid&quot;&gt;
                      &lt;div className=&quot;hat-business container&quot;&gt;
                          &lt;h1&gt;Доставка для бизнеса&lt;/h1&gt;
                          &lt;p&gt;Yams.uz осуществляет экспресс-доставку в мегаполисах, быстро, точно и надежно.&lt;/p&gt;
                          &lt;p&gt;Курьеры доставят ваши посылки в любую погоду, праздники и выходные. Yams.uz — это курьерская служба к платформе которой, подключены сотни клиентов и десятки тысяч исполнителей.&lt;/p&gt;
                          &lt;a href=&quot;#bid&quot; className=&quot;btn btn-primary&quot;&gt;Отправить заявку&lt;/a&gt;
                      &lt;/div&gt;
                      &lt;div className=&quot;bg-img-business&quot;&gt;
                          &lt;div className=&quot; container&quot;&gt;
                              &lt;div /&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
                      &lt;div className=&quot;business&quot;&gt;
                          &lt;div className=&quot;container&quot;&gt;
                              &lt;h2&gt;Для вашего бизнеса&lt;/h2&gt;
                              &lt;div className=&quot;row&quot;&gt;
                                  &lt;div className=&quot;col-12 mb-3 col-sm-10 mb-sm-3 offset-sm-1 col-md-6 offset-md-0 col-lg-4 mb-lg-0&quot;&gt;
                                      &lt;div className=&quot;card&quot;&gt;
                                          &lt;img src=&quot;/images/card-1.jpg&quot; className=&quot;card-img-top&quot; alt=&quot;для вашего бизнеса, одежда&quot; /&gt;
                                          &lt;div className=&quot;card-body&quot;&gt;
                                              &lt;h5 className=&quot;card-title&quot;&gt;Для вашего бизнеса, Одежда&lt;/h5&gt;
                                              &lt;p className=&quot;card-text&quot;&gt;Some quick example text to build on the card title and make up the bulk of the card's content.&lt;/p&gt;
                                              &lt;Link to=&quot;/&quot; className=&quot;btn btn-block btn-primary&quot;&gt;Подробнее&lt;/Link&gt;
                                          &lt;/div&gt;
                                      &lt;/div&gt;
                                  &lt;/div&gt;
                                  &lt;div className=&quot;col-12 mb-3 col-sm-10 mb-sm-3 offset-sm-1 col-md-6 offset-md-0 col-lg-4 mb-lg-0&quot;&gt;
                                      &lt;div className=&quot;card&quot;&gt;
                                          &lt;img src=&quot;/images/card-2.jpg&quot; className=&quot;card-img-top&quot; alt=&quot;аптеки&quot; /&gt;
                                          &lt;div className=&quot;card-body&quot;&gt;
                                              &lt;h5 className=&quot;card-title&quot;&gt;Аптеки&lt;/h5&gt;
                                              &lt;p className=&quot;card-text&quot;&gt;Some quick example text to build on the card title and make up the bulk of the card's content.&lt;/p&gt;
                                              &lt;Link to=&quot;/&quot; className=&quot;btn btn-block btn-primary&quot;&gt;Подробнее&lt;/Link&gt;
                                          &lt;/div&gt;
                                      &lt;/div&gt;
                                  &lt;/div&gt;
                                  &lt;div className=&quot;col-12 mb-3 col-sm-10 mb-sm-3 offset-sm-1 col-md-6 offset-md-0 col-lg-4 mb-lg-0&quot;&gt;
                                      &lt;div className=&quot;card&quot;&gt;
                                          &lt;img src=&quot;/images/card-3.jpg&quot; className=&quot;card-img-top&quot; alt=&quot;рассылка&quot; /&gt;
                                          &lt;div className=&quot;card-body&quot;&gt;
                                              &lt;h5 className=&quot;card-title&quot;&gt;Рассылка&lt;/h5&gt;
                                              &lt;p className=&quot;card-text&quot;&gt;Some quick example text to build on the card title and make up the bulk of the card's content.&lt;/p&gt;
                                              &lt;Link to=&quot;/&quot; className=&quot;btn btn-block btn-primary&quot;&gt;Подробнее&lt;/Link&gt;
                                          &lt;/div&gt;
                                      &lt;/div&gt;
                                  &lt;/div&gt;
                              &lt;/div&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
                      &lt;div className=&quot;send-bid&quot; id=&quot;bid&quot;&gt;
                          &lt;div className=&quot;container&quot;&gt;
                              &lt;h2&gt;Отправить заявку&lt;/h2&gt;
                              &lt;p&gt;Заполните данную форму и наши специалисты свяжутся 
                                  с вами в кратчайшие сроки, чтобы проконсультировать 
                                  вас о наших возможностях, предложить решение и подключить к системе&lt;/p&gt;
                              &lt;div className=&quot;row&quot;&gt;
                                  &lt;div className=&quot;col-12 col-lg-6&quot;&gt;
                                      &lt;div className=&quot;bid-form&quot;&gt;
                                          &lt;form onSubmit={this.bidHendler}&gt;
                                              &lt;input type=&quot;text&quot;
                                              className=&quot;form-control form-control-lg mb-3&quot; 
                                              placeholder=&quot;Как вас зовут&quot;
                                              name=&quot;name&quot;
                                              onChange={this.inputControl}
                                              value={name} /&gt;
                                              &lt;input type=&quot;phone&quot;
                                              className=&quot;form-control form-control-lg mb-3&quot; 
                                              placeholder=&quot;Введите номер телефона&quot;
                                              name=&quot;phone&quot;
                                              onChange={this.inputControl}
                                              value={phone} /&gt;
                                              &lt;button type=&quot;submit&quot; 
                                              className=&quot;btn btn-lg btn-block btn-business&quot;&gt;Отправить заявку&lt;/button&gt;
                                          &lt;/form&gt;
                                      &lt;/div&gt;
                                  &lt;/div&gt;
                              &lt;/div&gt;
                              &lt;div className=&quot;bid-form-footer&quot;&gt;
                                  &lt;p&gt;или позвоните нам по телефону:&lt;/p&gt;
                                  &lt;p&gt;+998 (90) 777-77-77&lt;/p&gt;
                                  &lt;p&gt;(Пн — Вс, 9:00 – 21:00)&lt;/p&gt;
                              &lt;/div&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          )
      }
  }
  
  export default ForBusinessPage;
  </code></pre>
  <p><em><strong>Help with the solution please, I will be very grateful!</strong></em></p>