#Is this good custom $fetch ?
3 messages · Page 1 of 1 (latest)
Based on the knowledge sources provided, I can offer some insights on your custom $fetch implementation for Nuxt. This implementation appears to be a good starting point, but there are a few considerations and potential improvements to note:
-
Base Structure: Your implementation follows the recommended pattern described in the Custom useFetch in Nuxt guide. It creates a custom
$fetchinstance within a Nuxt plugin, which is a good practice. -
Runtime Config: You're correctly using
useRuntimeConfig()to access configuration values, which aligns with the useRuntimeConfig documentation. -
Headers Handling: Your code handles headers appropriately, including setting the 'Accept' header and conditionally adding CSRF tokens for secure methods. This is in line with best practices for API requests.
-
Server-Side Request Handling: You're using
useRequestHeaders()to forward relevant headers during server-side rendering, which is a good practice mentioned in the Passing Headers and Cookies section of the Nuxt documentation. -
Error Handling: You've included hooks for request and response errors, which is important for proper error management.
However, there are a few points to consider:
-
Type Safety: Consider adding type annotations to improve type safety, especially for the
apiobject and the plugin return value. -
CSRF Token: The
useCsrfHeader()function is not a standard Nuxt function. Ensure this is a custom composable you've defined elsewhere in your project. -
Error Handling: The
useLaravelErrorHandler()function is also not standard. Make sure this is properly defined and handles errors appropriately.
-
Credentials: You're using
credentials: "include", which is fine if you intend to send cookies with every request. Just be aware of the security implications. -
Referer and Origin: Setting these headers manually might not be necessary in all cases, as browsers typically handle these automatically for client-side requests.
To improve this implementation, you might consider:
-
Using
useRequestFetch()as mentioned in the useRequestFetch documentation to automatically handle forwarding of headers in SSR contexts. -
Implementing a more robust error handling strategy, possibly using the
onResponseErrorhook to handle different types of errors (e.g., 401, 403, 500) in a centralized manner. -
Consider creating a custom
useAPIcomposable as shown in the Custom useFetch guide to wrap this custom fetch instance for easier use throughout your application.