Skip to content

useSanctumFetch()

useSanctumFetch() provides a pre-configured ofetch client tailored for use with Laravel Sanctum. This composable simplifies making API requests that require CSRF token management and cookie handling.

Features

  • CSRF Token Handling:
    The ofetch client provided by useSanctumFetch() automatically manages the CSRF token, ensuring that all requests to your Laravel backend are secure and authenticated.

  • Cookie Management:
    The client also handles cookies, particularly the CSRF token cookie, which is necessary for maintaining session security in Laravel.

  • Integration with useAsyncData(): You can use useSanctumFetch() in combination with Nuxt 3's useAsyncData() to handle data fetching in a reactive and efficient manner. Example:

    javascript
    const { data, status, error, refresh, clear } = await useAsyncData(
        'users', () => useSanctumFetch('/api/users')
    );
  • $Fetch Interface Compatibility:
    The client implements the $Fetch interface, meaning you can use it as you would with a regular ofetch client. This provides flexibility in how you structure and make API requests in your application.

For more advanced usage, refer to the ofetch documentation.

Base URL Configuration

All requests made with useSanctumFetch() will be sent to the apiUrl specified in your module's configuration. This ensures that all API calls are correctly routed to your Laravel backend.

javascript
export default defineNuxtConfig({
    // nuxt-sanctum-authentication options
    laravelSanctum: {
        // Replace with your Laravel API URL
        apiUrl: 'http://laravel-api.test',
    },
});