Skip to content Skip to sidebar Skip to footer

Error: Misconfigured Csrf - Express Js 4

I am trying to enable the csrf module of Express 4 in an existing application. I have added the following code: var csrf = require('csurf') ... app.use(csrf()); I have started my

Solution 1:

I have found the solution. The call to app.use(csrf()) must be set after app.use(cookieParser()) AND app.use(session({...}).

Solution 2:

If you're using Redis as a session store and the server isn't running, you will also get a misconfigured error.

https://github.com/expressjs/csurf/issues/73

Solution 3:

app.use(
  sessions({
  cookieName: 'demo-session',
  secret: 'this is a secret msg',
  duration: 30 * 60 * 1000,
 })
);

app.use(csurf({ sessionKey: 'demo-session' }));

I got the same error when the sessionKey was not the same in the session middleware and csurf. csurf uses session as default sessionKey if not provided. Here the sessionKey is demo-session, which should be the same in your session middleware.

Solution 4:

Step1: Install express-session and cookie-parser

npmiexpress-sessionnpmi-D @types/express-sessionnpmicookie-parsernpmi-D @types/cookie-parser

Step 2: In your main.ts file in your nest js project add the following lines of code

app.use(cookieParser());
app.use(
  session({
    secret: 'your-secret',
    resave: false,
    saveUninitialized: false,
  }),
);
app.use(csurf());

see the following cookie and session links for more details

Post a Comment for "Error: Misconfigured Csrf - Express Js 4"