CSRF mitigation for Next.js.
Mitigation patterns that next-csrf
implements:
- Synchronizer Token Pattern using
csrf
(Also read Understanding CSRF)
With yarn:
yarn add next-csrf
With npm:
npm i next-csrf --save
Setup:
Create an initialization file to add options:
// file: lib/csrf.js
import { nextCsrf } from "next-csrf";
const options = {
secret: process.env.CSRF_SECRET // Long, randomly-generated, unique, and unpredictable value
}
export const { csrf, csrfToken } = nextCsrf(options);
Create a setup endpoint:
// file: pages/api/csrf/setup.js
import { setup } from "../../../lib/csrf";
const handler = (req, res) => {
res.statusCode = 200;
res.json({ message: "CSRF token added to cookies" });
};
export default setup(handler);
On the first request, or any time you want to set up the CSRF token, send a GET request to the setup endpoint, in this example /api/csrf/setup
, and you will receive a cookie with the CSRF token on the response.
const response = await fetch('/api/csrf/setup');
if (response.ok) {
console.log('CSRF token setup')
}
Protect an API endpoint:
// file: pages/api/protected.js
import { csrf } from '../lib/csrf';
const handler = (req, res) => {
return res.status(200).json({ message: "This API route is protected."})
}
export default csrf(handler);
Every time you hit a protected API route you will replace the token in your cookie with a new one.