JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is cross-site request forgery (CSRF) in JavaScript apps?

Asked on Sep 07, 2024

Answer

Cross-Site Request Forgery (CSRF) is a security vulnerability that allows an attacker to trick a user into executing unwanted actions on a web application where they are authenticated. This can lead to unauthorized actions being performed on behalf of the user.
<!-- BEGIN COPY / PASTE -->
        // Example of a CSRF token implementation in a form submission
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        fetch('/submit-form', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'CSRF-Token': csrfToken // Include CSRF token in request header
            },
            body: JSON.stringify({ data: 'exampleData' })
        }).then(response => {
            if (response.ok) {
                console.log('Request successful');
            } else {
                console.error('Request failed');
            }
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  • CSRF attacks exploit the trust that a site has in a user's browser.
  • The code example demonstrates how to include a CSRF token in a request header to protect against CSRF attacks.
  • CSRF tokens are unique per session and should be validated on the server side.
  • Always ensure that sensitive actions require CSRF tokens to mitigate risks.
✅ Answered with JavaScript best practices.
← Back to All Questions