Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Edge Functions and Middleware in Next JS
Next article icon

Implementing Csurf Middleware in Node.js

Last Updated : 29 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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"
}

Steps to Implement Csurf Middleware in NodeJS:

Step 1: Create a file named app.js and import the required Modules.

const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

  • Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken(). 

Step 2: After Importing all the required modules, set up the route middleware and pass the validation method as a cookie instead of a token. Body-parser is used to parse the data coming from the form. Since a cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message. 

Step 3: Now, create a folder and named as view and create a file and name it login.ejs, and create a simple form as given below:

<form action="process" method="POST">
<input type="hidden" name="_csrf"
value="<%= csrfToken %>">
<input type="text" name="myname">
<input type="submit" value="Submit">
</form>

The above code example will run just as a simple application but there will be an added extra security measure for preventing CSRF.

Csurf Middleware Complete Example:

This example demonstrate a basic implementation of Csurf Middleware in Node.js.

HTML




<!-- Filename - login.ejs -->
<html>
<head>
    <title>Csurf Middleware</title>
</head>
 
<body>
    <form action="process" method="POST">
        <input type="hidden" name="_csrf"
               value="<%= csrfToken %>">
        <input type="text" name="myname">
        <input type="submit" value="Submit">
    </form>
</body>
</html>
 
 

Javascript




// Filename - app.js
 
const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
 
let csrfProtection = csrf({ cookie: true });
let parseForm = bodyParser.urlencoded({ extended: false });
 
let app = express();
app.set('view engine', 'ejs')
 
app.use(cookieParser());
 
app.get('/form', csrfProtection, function (req, res) {
    // pass the csrfToken to the view
    res.render('login', { csrfToken: req.csrfToken() });
});
 
app.post('/process', parseForm,
    csrfProtection, function (req, res) {
        res.send('Successfully Validated!!');
    });
 
app.listen(3000, (err) => {
    if (err) console.log(err);
    console.log('Server Running');
});
 
 

Steps to run this program: Run the app.js file with the following command:  

node app.js

Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: 

After submitting the form, you will see the following output: 

Successfully Validated!!

Conclusion:

Implementing csurf middleware in Node.js strengthens security by guarding against Cross-Site Request Forgery attacks. By generating and validating tokens, it protects sensitive user data, ensuring a robust defense. This proactive measure bolsters overall application integrity, providing a reliable shield against potential security vulnerabilities and unauthorized requests.



Next Article
Edge Functions and Middleware in Next JS
author
pranjal_srivastava
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • EJS-Templating Language
  • Node.js-Misc

Similar Reads

  • Edge Functions and Middleware in Next JS
    Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO
    4 min read
  • Next JS File Conventions: middleware.js
    In Next.js, the middleware.js file is one powerful tool to add custom functionality through the request/response cycle of the application. It is able to run some code before finalizing a request, which may involve actions such as authentication, logging, or even rewriting of URLs. Middleware can be
    7 min read
  • Built-in Middleware Functions in Express.js
    Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when ca
    4 min read
  • How to Build Middleware for Node JS: A Complete Guide
    NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application. Building middleware for
    5 min read
  • Middlewares in Next.js
    Middlewares in Next.js provide a powerful mechanism to execute custom code before a request is completed. They enable you to perform tasks such as authentication, logging, and request manipulation, enhancing the functionality and security of your application. Table of Content Middleware in Next.jsCo
    7 min read
  • Middleware in NestJS: Implementing Custom Middleware for Request Processing.
    Middleware in NestJS plays an important role in intercepting and processing HTTP requests before they reach route handlers. It allows developers to execute code logic before or after handling a request, making it a powerful tool for managing cross-cutting concerns such as logging, authentication, er
    3 min read
  • Explain the concept of middleware in NodeJS
    Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabli
    2 min read
  • Body-parser Middleware in Node.js
    Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. It's commonly used in web applications built with Express.js to handle form submissions, JSON payloads, and other types of request bodies. What is Body-
    3 min read
  • What is Middleware in Express.js ?
    Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
    2 min read
  • API Response Caching using apicache Middleware in Node.js
    APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a s
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences