Custom form submission with CSRF protection

If the use of granite.csrf.standalone client library is not amenable to your use case, you can manually add a CSRF token to a form submission. The following example shows how to add a CSRF token to a form submission.

This code snippet demonstrates how on form submit, the CSRF token can be fetched from AEM, and added to a form input named :cq_csrf_token. Because the CSRF token has a short life, it’s best to retrieve and set the CSRF token immediately before the form is submitted, ensuring its validity.

// Attach submit handler event to form onSubmit
document.querySelector('form').addEventListener('submit', async (event) => {
    event.preventDefault();

    const form = event.target;
    const response = await fetch('/libs/granite/csrf/token.json');
    const json = await response.json();

    // Create a form input named ``:cq_csrf_token`` with the CSRF token.
    let csrfTokenInput = form.querySelector('input[name=":cq_csrf_token"]');
    if (!csrfTokenInput?.value) {
        // If the form does not have a CSRF token input, add one.
        form.insertAdjacentHTML('beforeend', `<input type="hidden" name=":cq_csrf_token" value="${json.token}">`);
    } else {
        // If the form already has a CSRF token input, update the value.
        csrfTokenInput.value = json.token;
    }
    // Submit the form with the hidden input containing the CSRF token
    form.submit();
});