I am using nuxt 3.11.1 and when I am trying to send my requests from the server side I'm yet seeing the requests in network tab which made me doubt if I am sending them correctly or not.
I have written a composable for sending my requests which is like this:
export async function useData(endpoint, params, method = "POST") {
const authToken = useCookie("Authorization-Token");
const options = {
method,
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
};
if (method === "POST") {
options.body = { ...params };
}
try {
const response = await $fetch(
`${import.meta.env.VITE_API_BASE_URL}/v1/${endpoint}`,
options
);
return response;
} catch (error) {
throw error;
}
}
And in my page components I try to use this composable as the following:
const authToken = useCookie("Authorization-Token");
if (authToken.value) {
await useAsyncData(async () => {
fetchData();
});
}
async function fetchData() {
try {
const response = await useData("URL");
}
if the authToken does not exist I create my token and send my requests from the client side, but I also store the token in the cookies and will use it for the future requests. everything is working fine, but I'm seeing all of my requests in the network tab.
I also can not see the data in the payload tab of nuxt devtools
I changed the useData composable to use useFetch instead of $fetch and now I see any request but the first one and I also can see the requests in the payload tab of nuxt devtools.
here is the updated version of useData:
export async function useData(endpoint, params, method = "POST") {
return new Promise(async (resolve, reject) => {
const authToken = useCookie("Authorization-Token");
const options = {
method,
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
};
if (method === "POST") {
options.body = { ...params };
}
const {
data: { value: response },
error,
} = await useFetch(
`${import.meta.env.VITE_API_BASE_URL}/v1/${endpoint}`,
options
);
if (error.value) {
reject({
response: {
_data: {
code: error.value?.cause.response.status,
},
},
});
}
resolve(response);
});
}
Thanks to @Estus Flask and @Oleksandr, After updating useData composable and changing $fetch to useFetch I changed
if (authToken.value) {
await useAsyncData(async () => {
fetchData();
});
}
to
await useAsyncData(async () => {
if (authToken.value) {
await fetchData();
}
});
And now I only see the requests after navigating to a page. Yet I don't know why this fixed my problem but now I can be sure that the requests are being sent from the server side.