'Express CSURF returns ForbiddenError: invalid csrf token

Background

I have an Express app that uses TypeScript. I am intending to make a backend that will authenticate users and retrieve data etc.
I also have a react app that will call this backend separately via axios.

I have PassportJS local strategy for authentication in conjunction with Express-Session
So far so good. Until I decided to add CSRF protection with the csurf library that is suggested on the express documentation here

I followed the instructions exactly as provided on the documentation. Starting up the app didn't give my any issue. Without using csurf, I am able to make POST requests from my react app without any problem. However, after initialising csurf, when I made a post request, I got a 403 Forbidden error which the error message starts with:

ForbiddenError: invalid csrf token followed by some random paths

What I've tried

I believe that I am not the only one that is facing this issue in which there are quite a few other people who have asked the same. I've seen their suggestions but they don't seem to work nor do they address my issue of being unable to call from a React app. Needless to say, I've also tested doing POST requests via Postman and that did not work either

Code

The following is my code

import express, { request, Request, Response } from 'express'
import 'dotenv/config'
import passport from 'passport';
import session from 'express-session';
import clientController from './client/client';
import authController from './auth/auth.controller';
import saController from './superadmin/superadmin';
import cors from 'cors';
import csurf from 'csurf';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';

const app = express();
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors({
    credentials: true,
    origin: ['http://localhost:3000']
}));

const csrfMiddleware = csurf({ cookie: true })

const port = process.env.PORT
const sessionSecret = process.env.SESSION_SECRET

app.use(session({
    secret: sessionSecret!.toString(),
    resave: true,
    saveUninitialized: false,
    cookie: {
        httpOnly: true
    }
}))
app.use(csrfMiddleware)

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user: Object, done) => {
    console.log(user)
    done(null, user)
})

passport.deserializeUser((user: Object, done) => {
    done(null, user);
})

//Authentication route
const authRoute = authController
app.use('/auth', authRoute);

What I hope to get out of this

I have been going about this for a day or so and I hope someone has an answer to this problem. If not, I would hope that someone can suggest another library that I can use.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source