Created
April 12, 2025 19:40
-
-
Save johnston/db5e73111b99dbc66e0b0e58bef8943c to your computer and use it in GitHub Desktop.
Automatically add a CSRF token to requests with data-star
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { load } from "@starfederation/datastar/bundles/datastar-core" | |
| import * as plugins from "@starfederation/datastar/plugins" | |
| // Function to get CSRF token from meta tag | |
| const getCSRFToken = () => { | |
| const meta = document.querySelector('meta[name="csrf-token"]') | |
| return meta ? meta.getAttribute('content') : null | |
| } | |
| // Helper function to create CSRF-enabled HTTP method handlers | |
| const createCSRFHandler = (method) => ({ | |
| ...plugins[method], | |
| fn: async (ctx, url, args) => { | |
| const csrfToken = getCSRFToken() | |
| if (!args) args = {} | |
| return plugins[method].fn(ctx, url, { ...args, headers: { ...args.headers, 'X-CSRF-Token': csrfToken } }) | |
| } | |
| }) | |
| // Create CSRF-enabled handlers for all HTTP methods | |
| const HTTP_METHODS = ['POST', 'DELETE', 'PUT', 'PATCH'] | |
| const csrfHandlers = HTTP_METHODS.reduce((acc, method) => { | |
| acc[method] = createCSRFHandler(method) | |
| return acc | |
| }, {}) | |
| // Load all plugins, using CSRF-enabled handlers where available | |
| Object.keys(plugins).forEach(key => { | |
| if (csrfHandlers[key]) { | |
| load(csrfHandlers[key]) | |
| } else { | |
| load(plugins[key]) | |
| } | |
| }) |
Author
@alvarolm Ultimately we moved away from using Datastar so this isn't something I'm likely to be able to update in the foreseeable future.
thank you for the response!
out of curiosity, what you end up using instead ?
Author
@alvarolm We went back to using Hotwire/Turbo/Stimulus. Best of luck with the datastar-resources project.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for sharing, with rc6 the plugin API changed, so sadly this no longer works.
I would lo to feature a working version in https://github.com/alvarolm/datastar-resources