This content originally appeared on DEV Community and was authored by DEV Community
Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to submit a request to a Web application against which they are currently authenticated.
It ensures the authenticity of your requests.
We will use a popular npm package to handle CSRF called csurf.
Because csurf is express middleware, and there is no easy way to include express middlewares in next.js applications we have two options.
1- Create custom express server and use the middleware, check this link
2- Connect express middleware, we will follow this method, more details in next.js docs
we will create new file /src/csrf.js
import csurf from 'csurf'
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export function csrf(req, res) {
return new Promise((resolve, reject) => {
csurf({ cookie: true })(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export default csrf
Now we have two steps to implement this,
1- Make sure the API is protected by CSRF token.
Lets take the default API route that comes with initial next.js project "hello.js", to include the middleware we need to do the following
import csrf from "../../src/csrf";
export default async function handler(req, res) {
await csrf(req, res);
res.status(200).json({ name: 'John Doe' })
}
This way we are protecting this route with CSRF token
2- Expose this token to the react page so it can be sent with the requests.
To get the token
export async function getServerSideProps(context) {
const { req, res } = context
await csrf(req, res)
return {
props: { csrfToken: req.csrfToken() },
}
}
Now on the next API call to hello.js we need to include the token in the header, here I used axios but you can use fetch as well
axios.post('http://localhost:3000/api/hello', {}, {headers:{'CSRF-Token': csrfToken}})
.then(res=>console.log({data: res.data}))
And that's it, Now you are protected against CSRF attacks
Note that you can add more options to your cookie like make it HttpOnly and change the key name, check the library docs for more details.
This content originally appeared on DEV Community and was authored by DEV Community

DEV Community | Sciencx (2022-03-07T22:53:29+00:00) CSRF Protection in Next.js. Retrieved from https://www.scien.cx/2022/03/07/csrf-protection-in-next-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.