Skip to content
Advertisement

ForbiddenError: invalid csrf token, express js

I’ve tried to get csurf to work but seem to have stumbled upon something. The code so far looks like this:

index.ejs

JavaScript

Where you insert password and username in the form.

app.js

JavaScript

Where I’ve put csrf after session and cookie parser.

index.js

JavaScript

What I get after submiting the form, no matter if I insert the correct username and password or not I still get the same error:

JavaScript

Also I want add that I’ve been working with node for about 2 weeks, so there is still alot I need to learn probably.

Advertisement

Answer

{{csrfToken}} isn’t an EJS construction, so it’s not expanded at all and is probably sent literally to your server.

This should work better:

JavaScript

The middleware is setting csrftoken though, with lowercase ‘t’, where the template expects an uppercase ‘T’:

JavaScript

You also generate two different tokens, which is probably not what you want. Store the token in a variable and reuse that:

JavaScript

And lastly, you probably have to move your middleware to before the route declarations, otherwise it won’t be called:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement