Blog>
Snippets

Protecting Against CSRF Attacks with Error Handling

Demonstrate the integration of CSRF protection in a Next.js app and handle errors related to CSRF token validation.
import csrf from 'csurf';
import nextConnect from 'next-connect';

const csrfProtection = csrf({ cookie: true });
const handler = nextConnect();

handler.use(csrfProtection);

handler.post(async (req, res) => {
  // Your POST logic here
});

export default handler;
This code snippet sets up CSRF protection using the csurf library with Next.js API routes. It creates a middleware for CSRF token generation and validation, and applies it to the POST request handler.
<form method="post" action="/api/your-endpoint">
  <input type="hidden" name="_csrf" value="{csrfToken}" />
  <!-- Your form fields here -->
  <button type="submit">Submit</button>
</form>
This HTML form includes a hidden input field for the CSRF token. The value should be set to the CSRF token generated by the server-side code.
export default function getServerSideProps(context) {
  //... Your server-side logic before responding
    return {
        props: { csrfToken: req.csrfToken() },
    };
}
This Next.js function is used to pass the CSRF token generated on the server to the client-side, which will be used to populate the hidden input field in the form.
handler.use((err, req, res, next) => {
  if (err.code !== 'EBADCSRFTOKEN') return next(err);

  // handle CSRF token errors here
  res.status(403);
  res.send('form tampered with');
});
This middleware catches errors related to CSRF token validation. If there is a CSRF token error, it sends a response with status code 403 and an error message.