Skip to content

Instantly share code, notes, and snippets.

@johndwells
Created July 21, 2023 16:49
Show Gist options
  • Save johndwells/cadad15112c0aa5915e5590ad47f92d2 to your computer and use it in GitHub Desktop.
Save johndwells/cadad15112c0aa5915e5590ad47f92d2 to your computer and use it in GitHub Desktop.
Refreshing Craft CSRF tokens using Unpoly
import "unpoly";
/**
* Helper to fetch user session info
* https://craftcms.com/docs/4.x/dev/controller-actions.html#ajax
*/
const getSessionInfo = function() {
return fetch('/actions/users/session-info', {
headers: {
'Accept': 'application/json',
},
})
.then(response => response.json());
};
/**
* CSRF injection
* When any fragment is inserted into the DOM, query for any hidden CSRF inputs.
* If one or more found, get user session info via AJAX, and then update all inputs
* with the csrf token value contained in the response.
*/
up.on('up:fragment:inserted', function(event, fragment) {
var inputs = fragment.querySelectorAll('[name=' + window.CSRF_TOKEN_NAME + ']');
if( ! inputs) {
return;
}
try {
getSessionInfo()
.then(session => {
inputs.forEach(function(el) {
el.value = session.csrfTokenValue;
});
});
} catch (error) {
console.error('Error fetching token:', error);
}
});
<script type="text/javascript">
window.CSRF_TOKEN_NAME = '{{ craft.app.config.general.csrfTokenName|e('js') }}';
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment