Some days ago I had to develop a small authentication app in Node with the Express framework. Basically it exposes just one JSON API, something like POST /user_data. It accepts two parameters: user and password and returns the data if they are correct.

Users are created by an administrator using a web interface. Of course every form is protected from CSRF using Express’ middleware.

Following the official guide you have to do so in order to enable it:

That’s correct if you want to validate every POST request. In my case I needed to skip the CSRF control for my API. So I defined my own middleware function that skips /user_data requests:

In this way CSRF token validation will be applied only on POST requests not in the whitelist array.

If you want you can also skip validation for every AJAX requests. Here’s the code: