To implement CSRF (Cross-Site Request Forgery) protection when using the Fetch API, you'll typically
follow these steps:
1. Set Up CSRF Token in Your Backend
1. Generate a CSRF Token: Your server should generate a unique CSRF token for each user session
or request. This can be done using libraries available in your backend language/framework.
2. Send the Token to the Client: Include the CSRF token in the HTML response, either as a meta
tag or in a cookie.
2. Include the CSRF Token in Fetch Requests
When making requests with the Fetch API, you'll need to include the CSRF token in the request headers.
Example in JavaScript
// Assuming you have a CSRF token available in a meta tag
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('/your-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken // Include the CSRF token here
},
body: JSON.stringify({
// your data here
})
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
3. Validate CSRF Token on the Server
On your server, you need to check the CSRF token sent in the request headers against the one stored in
the user's session. If they don't match, you should reject the request.
4. Additional Considerations
● Same-Origin Policy: Ensure your CSRF token is not accessible by cross-origin requests. Consider
using SameSite cookies for added security.
● HTTP Method Restrictions: CSRF attacks typically target state-changing methods (like POST,
PUT, DELETE). Make sure your CSRF protection is applied to those methods specifically.
● CORS: If your frontend and backend are on different origins, ensure that you handle CORS
correctly, allowing your frontend to send the CSRF token.
By following these steps, you can effectively protect your application from CSRF attacks when using the
Fetch API.