How can I get data from api when backend is secured by laravel sanctum?
when I use useFetch
I do not get any data.
const {data: cat} = await useFetch('/api/categories')
Laravel docs told to use axios but in nuxt3 axios module not working.
Can someone help?
I was try use useFetch
with method get to get csrf cookie but it’s doesn’t work
const {data} = await useFetch('/sanctum/csrf-cookie', {method: 'get'}).then(Response => {
})
4
Answers
To get data when using sanctum,
You are already getting the csrf token above by going to the route /sanctum/csrf-cookie.
However, that is not enough.
For every request that you want to make which is secured, you need to send a token that is generated using sanctum.
Usually, for an app, you would follow these steps
The header would be something like this
All depends how you are sending the request.
More documentation is available On this link on Laravel Documentation
Also, ensure you have
As part of your headers as well.
If you do not send that token in your headers, your requests will give you an error "Unauthenticated".
Below is an example of what I send to the API
And for Authorization, select the option of Bearer Token
Hope this helps.
The endpoint
/sanctum/csrf-cookie
does not return content in the body of the response, that’s why you getHTTP 204 No Content
, during this request Laravel Sanctum will set anXSRF-TOKEN
cookie containing the current CSRF token, you have two ways to use the token: it can be passed viaX-XSRF-TOKEN
header from your requests, or from the originalXSRF-TOKEN
cookie.https://laravel.com/docs/9.x/sanctum#csrf-protection
Here’s an exemple using the XSRF-TOKEN cookie:
I am working on simple package enabling easy integration of laravel sanctum with nuxt3. Maybe it can help you until official auth module for nuxt3 is released.
https://github.com/dystcz/nuxt-sanctum-auth
Currently, the useFetch or the $fetch doen’t return or allow access to the xsrf-cookie. So instead try using axios which automatically appends the xsrf-cookie return from /sanctum/csrf-cookie/ call. To use axios on nuxt3 app you need to create a custom plugin for the axios module.
Here is a link https://www.the-koi.com/projects/nuxt-3-how-to-use-axios/ to direct you. It works perfectly for me as it appends the xsrf header return by /sanctum/csrf-cookie/ and uses it for subsequent API calls