Skip to content

3 Techniques For Better Protecting Against NextJS CSRF Attacks

Protecting Next.js applications against CSRF attacks is vital in maintaining data integrity and user security, especially with Vercel Logging. In times of increasing cyber threats, safeguarding your web applications is crucial. By learning how to defend your Next.js applications against CSRF attacks, you can ensure a smooth user experience and maintain their trust.

Introducing Alerty's solution, NextJS logging, an effective tool to help you achieve the goal of securing your Next.js applications against CSRF attacks.

Table of Contents

What Is a CSRF Attack?

Woman Using Computer - NextJS CSRF

Cross-site request Forged (CSRF) is a type of attack in which unauthorized commands are transmitted from a user that a web application trusts. CSRF attacks exploit the trust a web application has in a user's browser. When the user is authenticated, the attacker tricks the browser into making an unwanted request to the web application on behalf of the user. This can lead to unauthorized actions like data manipulation, state changes, or sensitive information exposure.

Web Application Attacks That Exploit User Trust

These attacks exploit the trust established between users and web applications, taking advantage of the implicit trust placed in an authenticated user’s session within the context of a web application.

After a user signs into an application, the application creates a session that authenticates the user’s identity for future requests. This authentication allows the user to access protected resources and perform certain operations within the application.

Social Engineering for Session Hijacking

An attacker can exploit this trust by sending malicious requests that include necessary parameters and instructions to carry out specific actions, such as making unauthorized financial transactions. Typically, this is done by tricking the victim into visiting a specially designed webpage or clicking on a malicious link.

The Impact of Forged Requests on Web Applications

When users visit a malicious page or click on a link, their browser can send a forged request to a targeted web application without their knowledge. If the user was previously authenticated in the application, the server may regard the request as valid and process it, allowing undesired operations to be carried out on the user’s behalf without their knowledge or agreement.

Related Reading

How CSRF Attacks Occur on Unprotected Webpages

Person Using Computer - NextJS CSRF

User Authentication

When a user logs into a web application using their credentials, such as logging into a banking site like examplebank.com, the application authenticates the user and stores a session cookie in the user's browser to keep them logged in.

User Visits Malicious Site

While logged into the banking site, the user visits another website, which in this case is malicious (attackersite.com). This malicious site can contain hidden forms or scripts designed to make unauthorized requests to the banking site on behalf of the user.

Execution of Malicious Request

The malicious site, attackersite.com, automatically sends a request to the banking site, examplebank.com, without the user's knowledge. Since the user is already authenticated on the banking site, their browser automatically includes the session cookie with the request. The banking site processes the request as if it were made by the authenticated user, performing actions like transferring funds or changing account settings.

Catch Issues Early with Alerty's Cloud Monitoring

Alerty is a cloud monitoring service designed specifically for developers and early-stage startups. It offers application performance monitoring, database monitoring, and incident management solutions. This innovative platform supports various technologies, enabling developers to identify and address potential issues efficiently; this includes:

  • NextJS
  • React
  • Vue
  • Node.js

With Alerty, users can monitor databases such as Supabase, PostgreSQL, and RDS, tracking key metrics like CPU usage and memory consumption. It features quick incident management and Real User Monitoring (RUM) to optimize user experience. 

Alerty's Universal Service Monitoring covers a wide range of dependencies, including popular APIs like:

  • Stripe
  • OpenAI
  • Vercel

By providing visibility into the performance of these dependencies, Alerty enables developers to ensure that their applications are running smoothly and efficiently. 

Catch issues before they affect your users with Alerty's NextJS logging tool today!

 

Simulating A CSRF Attack

Hacker Using Computer - NextJS CSRF

To understand how a CSRF attack works, let's walk through a simulation of an attack on a fictional banking application, examplebank.com. We'll assume the user is already authenticated on examplebank.com, and we'll create a malicious site, attackersite.com, to carry out the attack.

Setup

User Authentication

User logs into examplebank.com.

The application sets a session cookie in the user's browser.

Malicious Website

The attacker sets up attackersite.com with a hidden form miming a legitimate request to examplebank.com.

Step-by-Step Simulation

User Logs into ExampleBank

<!-- User logs in and gets a session cookie -->

<form action="https://examplebank.com/login" method="POST">

  <input type="text" name="username" value="user123">

  <input type="password" name="password" value="password">

  <button type="submit">Login</button>

</form>

ExampleBank Sets Session Cookie

Upon successful login, examplebank.com sets a session cookie in the user’s browser.

User Visits Malicious Website

While still logged into examplebank.com, the user visits attackersite.com, which could have been an email sent by the attacker to trick the user into visiting their site.

The malicious site contains a hidden form to transfer money from the user’s account.

Hidden Form on Attacker Site

<!-- Hidden form on attackersite.com -->

<html>

  <body>

    <h1>Check out this awesome deal!</h1>

    <form action="https://examplebank.com/transfer" method="POST" style="display:none;">

      <input type="hidden" name="amount" value="1000">

      <input type="hidden" name="recipient" value="attacker_account">

      <button type="submit">Transfer Money</button>

    </form>

    <script>

      // Automatically submits the form when the page loads

      document.forms[0].submit();

    </script>

  </body>

</html>

Automatic Form Submission

The script in the form automatically submits the request to examplebank.com when the page loads.

Request Sent with Session Cookie

The user’s browser includes the session cookie with the form submission, as the user is still logged in to examplebank.com.

Bank Processes the Request

The banking application receives the request with the session cookie and treats it as an authenticated request from the logged-in user. The money transfer is processed, and the funds are moved from the user's account to the attacker's.

Simulating a CSRF Attack

This simulation of a CSRF attack demonstrates how an attacker can manipulate an authenticated user's session to carry out malicious actions without the user's consent or knowledge. If not properly mitigated, such attacks can result in unauthorized transactions, data theft, or other harmful activities.

3 Best Techniques for Better Protecting Against NextJS CSRF Attacks

person Using Laptop - NextJS CSRF

1. Verifying Referer Headers

The Referer header plays a crucial role in website security. It is an essential component of the HTTP protocol that allows servers to identify the webpage URL that referred a user to the current page. This header is included in subsequent requests sent to the server when a user acts on a website. By validating the Referer header, we can check if requests originate from trusted sources, thus preventing CSRF attacks that manipulate users into performing undesirable actions. 

A Complementary Defense for CSRF Attacks

It is essential to note that attackers can modify or remove the Referer header, making it a supplementary defense mechanism rather than a standalone protection measure against CSRF attacks.

2. SameSite Cookies

One way to enhance the security of your Next.js application against CSRF attacks is by utilizing the SameSite value inside the cookies employed on your website. Google introduced this attribute in 2006 to prevent cookies from being automatically sent along with cross-site requests by web browsers. This update aimed to minimize the risk of compromising sensitive information and provide protection against cross-site request forgery. 

Enhanced Security With Re-authentication

The SameSite attribute can take either "strict" or "lax" as its value. In strict mode, the protected cookie is not transmitted with any cross-site request, leading to users needing to re-authenticate themselves each time they are redirected to specific pages.

Balancing Security With Usability for Specific Requests

Lax mode allows the cookie to be sent with secure cross-site requests, benefiting secure, read-only HTTP methods and top-level navigation actions that trigger changes in the browser's address bar, such as links.

3. Using CSRF Tokens

CSRF tokens are invaluable in safeguarding against CSRF attacks. These tokens are unique, randomly generated values linked to each user session. By mandating a valid CSRF token with each request, attackers cannot access the token, even if they successfully deceive a user into sending a malicious request. This approach helps prevent unauthorized activities by allowing the server to differentiate between legitimate and malicious requests.

Utilizing CSRF Tokens with Next.js Middleware

Next.js simplifies utilizing CSRF tokens by offering an integrated mechanism, including CSRF protection middleware. Tokens are generated and included in forms or responses. They can be authenticated when subsequent requests are received. CSRF tokens are a commonly employed and effective strategy for preventing CSRF attacks.

Related Reading

Implementing NextJS CSRF Protection

Multiple Screen Computer - NextJS CSRF

To protect against Cross-Site Request Forgery (CSRF) attacks in Next.js applications, you can utilize a package called next-csrf. This package simplifies the process of implementing CSRF protection by following these steps:

Generate and Send CSRF Token

The server generates and sends a CSRF token to the client.

Submit Form With Token

The client/browser submits a form that includes the CSRF token.

Validate Token

The server checks if the token is valid. Installing the next-csrf package involves running the following command in your Next.js project root:

```bash
npm i next-csrf --save
```

To set up the CSRF token, you can create a setup file that initializes next-csrf. This file will contain middleware for generating and validating CSRF tokens. Here’s an example setup file:

```javascript
// "lib/csrf"
import { nextCsrf } from "next-csrf";

const { csrf, setup } = nextCsrf({
secret: "12345", // Store your secret securely in production
});

export { csrf, setup };
```

Next, you can protect your pages or API routes by leveraging the CSRF middleware. Consider the following example with a server-side rendered page:

```javascript
import Head from "next/head";
import { setup } from "lib/csrf";

export default function Home() {
return (
  // Your component content here
);
}

export const getServerSideProps = setup(async ({ req, res }) => {
return {
  props: {}, // Props for your component
};
});
```

For API routes, you can wrap the corresponding handler with the CSRF middleware, like in the example below:

```javascript
// src/pages/api/transfer.js
import { csrf } from "../../../lib/csrf";

const handler = (req, res) => {
  // Check request method
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method Not Allowed' });
    return;
  }
 
  // Check for session cookie
  if (!req.cookies.session) {
    res.status(401).json({ error: 'Unauthorized' });
    return;
  }
 
  // Extract data from the request body
  const { name, iban, amount } = req.body;
 
  // Return success message
  res.status(200).json({ name, iban, amount });
}

export default csrf(handler);
```

By incorporating the next-csrf package and following these steps, you can enhance the security of your Next.js applications against CSRF attacks. This approach ensures that requests come from authenticated users, mitigating the risk of unauthorized actions.

Essential Considerations for CSRF Protection

Lock on a Keyboard - NextJS CSRF

CSRF Token Storage

CSRF tokens are essential for verifying the legitimacy of a request and its origin within the user's session. These tokens are typically stored in cookies or sent as hidden form fields in web forms.

Importance of Unique CSRF Tokens

A significant consideration for implementing CSRF protection includes generating unique tokens per session or request. This uniqueness helps prevent token reuse and reduces the likelihood of token prediction.

Protecting CSRF Tokens

It is crucial to store these tokens securely to prevent unauthorized access. When stored in cookies, they must be marked as HTTPOnly and Secure to mitigate risks. To ensure that CSRF tokens are effectively checked server-side before processing any sensitive actions, they must be included in HTTP requests, either in headers or as hidden form fields.

SameSite Cookies

Setting the SameSite attribute for cookies is another critical aspect to consider when implementing CSRF protection. This is an additional security measure to prevent CSRF attacks. 

This attribute can be set to three different values

  • Strict
  • Lax
  • None

Strict

When set to Strict, cookies are not sent with cross-site requests, enhancing security. Yet this setting may impact user experience for third-party integrations. 

Lax

Lax setting withholds cookies on cross-site subrequests but sends them when a user navigates to the URL from an external site. This setting balances security and usability. 

None

The None setting ensures that cookies are sent in all contexts, but it must be used with the Secure attribute to ensure transmission only over HTTPS. By setting the SameSite attribute appropriately, browsers are prevented from sending cookies with cross-site requests, thus mitigating the risk of CSRF attacks.

HTTPS

Utilizing HTTPS is a non-negotiable requirement for secure web applications. HTTPS ensures that all data transmitted between the user's browser and the web server is encrypted, thus preventing interception and tampering by malicious actors. Particularly for CSRF protection, transmitting CSRF tokens over HTTPS encrypts them, making it challenging for attackers to intercept or manipulate them. 

HTTPS guarantees the integrity and authenticity of the data, providing users with the confidence that they are interacting with a legitimate and secure application.

Related Reading

Ensure a Smooth User Experience by Catching Next.js Issues Early With Alerty

Alerty is a cloud monitoring service designed specifically for developers and early-stage startups. It offers application performance monitoring, database monitoring, and incident management solutions. This innovative platform supports various technologies, enabling developers to identify and address potential issues efficiently; this includes:

  • NextJS
  • React
  • Vue
  • Node.js

Streamlining Resolution for Developers

With Alerty, users can focus on helping developers identify and resolve issues promptly. 

Key Metrics Monitored by Alerty

  • Supabase
  • PostgreSQL
  • RDS
  • CPU usage
  • Memory consumption

This cloud monitoring service also incorporates quick incident management and Real User Monitoring (RUM) to optimize user experience.

Efficient Incident Management and Monitoring Capabilities

One of Alerty's notable features is its Universal Service Monitoring, which encompasses dependencies like the: 

Stripe API

OpenAI

Vercel. 

This broad coverage enables developers to gain insights into all aspects of their applications, ensuring holistic monitoring. 

AI-Powered Setup for Developers and Small Teams

Alerty employs artificial intelligence to streamline the setup process, making it a cost-effective solution compared to other competitors in the market. This focus on simplifying setup and lowering costs makes Alerty ideal for developers and small teams seeking efficient and affordable cloud monitoring solutions.

Seamless Integration and Ease of Use

Alerty goes the extra mile by integrating with other tools, such as Sentry, allowing for a more streamlined monitoring experience. This integration gives developers a cohesive and efficient approach to monitoring their applications. Alerty's user-friendly design makes the setup process quick and easy, catering to the needs of developers who value simplicity and efficiency in their monitoring solutions. 

Catching issues before they impact end-users is crucial, and Alerty's NextJS logging tool is geared toward achieving this goal effectively.

Why Alerty is Ideal for Developers and Startups

Alerty presents a compelling option for developers and early-stage startups seeking cost-effective cloud monitoring solutions. With its comprehensive monitoring capabilities, efficient incident management, and seamless integration with other tools, Alerty stands out as a valuable asset in cloud monitoring services. 

Start monitoring your applications effectively today with Alerty's NextJS logging tool!