Search code examples
node.jsexpresscsrf

NodeJS: misconfigured csrf


I am trying to run a nodejs app. The problem that I have however is every time I try to run the app, it throws an error as stated in the title: misconfigured csrf.

Here is my code:

const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const csrf = require('csurf');
const flash = require('connect-flash');

const errorController = require('./controllers/error');

const User = require('./models/user');

const MONGODB_PASS = 'PASSWORD_HERE';

const MONGODB_URI = `mongodb+srv://USER_HERE:${MONGODB_PASS}@DB_HOST_HERE/shop?retryWrites=true&w=majority`;

const app = express();
const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});
const csrfProtection = csrf({cookie: true});

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const authRoutes = require('./routes/auth');

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'my secret',
  resave: false,
  saveUninitialized: false,
  store
}));
app.use(csrfProtection);
app.use(flash());

app.use((req, res, next) => {
  if (!req.session.user) return next();
  User.findById(req.session.user._id).then(user => {
    req.user = user;
    next();
  }).catch(err => {throw err});
});

app.use((req, res, next) => {
  res.locals.isAuthenticated = req.session.isLoggedIn;
  req.locals.csrfToken = req.csrfToken();
  next();
});

app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);

app.use(errorController.get404);

mongoose.connect(MONGODB_URI)
  .then(result => app.listen(3000)).catch(err => { throw err });

I expect the app to run successfully but instead, it throws an error saying: misconfigured csrf. What am I doing wrong?

Note: I seriously don't know what to write anymore and SO keeps complaining that i need to add some more details. I believe i've provided enough explanation with the description, the title, and the code.


Solution

  • You are using the cookie option:

    const csrfProtection = csrf({cookie: true});
    

    It requires the cookie-parser package as documented here: If you are setting the "cookie" option to a non-false value, then you must use cookie-parser before this module.