Skip to content

Instantly share code, notes, and snippets.

@johnston
Created April 12, 2025 19:40
Show Gist options
  • Select an option

  • Save johnston/db5e73111b99dbc66e0b0e58bef8943c to your computer and use it in GitHub Desktop.

Select an option

Save johnston/db5e73111b99dbc66e0b0e58bef8943c to your computer and use it in GitHub Desktop.
Automatically add a CSRF token to requests with data-star
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])
}
})
@alvarolm
Copy link

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

@johnston
Copy link
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.

@alvarolm
Copy link

thank you for the response!
out of curiosity, what you end up using instead ?

@johnston
Copy link
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