Created
May 8, 2023 03:13
-
-
Save kriansa/0e8db2abdfcfcb601d514c589d478c22 to your computer and use it in GitHub Desktop.
Enable CSRF on Nuxt/Axios for Rails APIs
This file contains 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
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