Steps to set up the Application and Installing Required Modules
Step 1: First, we need to initialize our application with a package.json file. Therefore, write the following command in the terminal:
npm init
Step 2: After the package.json is created, it’s time to install our dependencies. Therefore, Install the required dependencies by the following command:
npm install body-parser cookie-parser express csurf --save
Here,
- Cookie-parser is used to parse the incoming cookies.
- Body-parser is used to parse the incoming form data that we will be creating in an HTML file.
Updated dependencies in the package.json file.
"dependencies": {
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"csurf": "^1.11.0",
"express": "^4.18.2"
}
Implementing Csurf Middleware in Node.js
Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSRF token as a cookie. The token sent will be different for each request since they are generated randomly.