Composables
useEnsureCsrf
Ensure CSRF token is available for Sanctum requests
useEnsureCsrf is a composable that ensures a CSRF token is available for Sanctum authentication. It automatically fetches the CSRF token if it doesn't exist and synchronizes it with the auth headers.
Usage
await useEnsureCsrf();
Or with an explicit auth instance:
const { $auth } = useNuxtApp();
await useEnsureCsrf($auth);
Behavior
The composable follows this logic:
- Check for existing CSRF token: Looks for the
XSRF-TOKENcookie - If token exists: Synchronizes it with the auth headers and returns
- If token doesn't exist: Fetches a new CSRF token from the configured endpoint
Examples
Basic Usage
await useEnsureCsrf();
Before Custom Request
// Ensure CSRF token before making a custom request
await useEnsureCsrf();
const data = await $fetch('/api/custom', {
method: 'POST',
body: { data: 'value' }
});
With Auth Instance
const { $auth } = useNuxtApp();
await useEnsureCsrf($auth);
In Component Setup
<script setup>
onMounted(async () => {
// Ensure CSRF token when component mounts
await useEnsureCsrf();
});
</script>
Before Form Submission
const handleSubmit = async () => {
// Ensure CSRF token before submitting form
await useEnsureCsrf();
const { $auth } = useNuxtApp();
await $auth.login({
strategy: 'client',
email: form.value.email,
password: form.value.password
});
};
How It Works
Cookie Check
The composable checks for the XSRF-TOKEN cookie:
const xsrf = useCookie<string | null>('XSRF-TOKEN').value;
Header Synchronization
If the cookie exists, it decodes and sets the header:
$auth.headers.set('X-XSRF-TOKEN', decodeURIComponent(xsrf));
Token Fetching
If the cookie doesn't exist, it calls the auth instance's CSRF method:
await $auth.csrfToken();
When to Use
You typically don't need to call useEnsureCsrf directly because:
$autxautomatically calls it for POST, PUT, PATCH, DELETE requests- The auth module's built-in methods handle it internally
However, you might need it when:
- Making custom requests with
$fetchinstead of$autx - Implementing custom authentication flows
- Debugging CSRF-related issues
Complete Example
<script setup>
const { $auth } = useNuxtApp();
const customRequest = async () => {
// Ensure CSRF token before custom request
await useEnsureCsrf($auth);
// Make custom request
const response = await $fetch('/api/custom', {
method: 'POST',
headers: {
// CSRF header is already set by useEnsureCsrf
},
body: {
data: 'value'
}
});
return response;
};
const submitForm = async () => {
// Ensure CSRF before form submission
await useEnsureCsrf($auth);
// Submit form data
await $auth.login({
strategy: 'client',
email: 'user@example.com',
password: 'password'
});
};
</script>
Notes
- This composable is specific to the Sanctum provider
- It has no effect when using the Passport provider
- The CSRF endpoint is configured via the
csrfoption innuxt.config.ts - The composable is async and should be awaited