Skip to content

Instantly share code, notes, and snippets.

@kriansa
Created May 8, 2023 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kriansa/0e8db2abdfcfcb601d514c589d478c22 to your computer and use it in GitHub Desktop.
Save kriansa/0e8db2abdfcfcb601d514c589d478c22 to your computer and use it in GitHub Desktop.
Enable CSRF on Nuxt/Axios for Rails APIs
export default function ({ $axios }) {
// Because API is always considered as a cross-domain call, the default
// XSRF feature available on axios will not work for us, because they use
// cookies and cookies aren't readable in cross-domains. Instead we must
// rely on having CSRF sent on every header request by the backend, and
// then we store that value to send on the next subsequent request.
//
// See: https://github.com/axios/axios#interceptors
$axios.interceptors.request.use((config) => {
if (!config.method.includes('get', 'head', 'options')) {
config.headers['X-CSRF-Token'] = globalThis.XSRF_TOKEN
}
return config
})
$axios.interceptors.response.use((response) => {
globalThis.XSRF_TOKEN = response.headers['x-csrf-token']
return response
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment