Skip to content

Instantly share code, notes, and snippets.

@noahd1
Last active April 24, 2024 20:17
Show Gist options
  • Save noahd1/8210adff1021a22336331ecc38939462 to your computer and use it in GitHub Desktop.
Save noahd1/8210adff1021a22336331ecc38939462 to your computer and use it in GitHub Desktop.
csrf_refresh
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = {
wait: Number
}
connect() {
this.refresh = this.debounce(this.refreshNoBounce, this.waitValue || 500); // Default wait time of 500ms if not specified
}
debounce = (func, wait) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
refreshNoBounce = () => {
fetch('/refresh_csrf', {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => {
document.querySelector('meta[name="csrf-token"]').setAttribute('content', data.csrf);
document.querySelectorAll('input[name="authenticity_token"]').forEach((el) => {
el.value = data.csrf;
});
})
.catch(error => console.error('Error refreshing CSRF token:', error));
}
}
class CsrfController < ActionController::Base
def refresh
render json: { csrf: form_authenticity_token }
end
end
<body data-controller="csrf" data-action="focus@window->csrf#refresh">
</body>
Rails.application.routes.draw do
# ...
get '/refresh_csrf', to: 'csrf#refresh'
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment