Help Needed: Nuxt 3 – Ensuring SSR-Only API Calls & Preventing CSR Requests During Navigation

Hi everyone, I'm currently working on a Nuxt 3 application with multiple pages, and I've encountered some issues with SSR and CSR behavior during navigation: My Use Case I'm using useAsyncData directly within the <script setup> tag (with TypeScript) to fetch data from APIs for each page. I want all API calls to be executed only on the server side so that the fully-rendered HTML is sent to the client without any additional client-side API requests. When I navigate between pages using nuxt-link, the API calls show up in the network tab, indicating that they're being made on the client side, which I want to avoid. When I refresh a page, the API calls are made on the server, at this point the token stored in Cookie using useCookie is undefined, making my request unauthenticated. My Goals I want to ensure that all API calls are handled only on the server side, even when navigating between pages using nuxt-link. I also want to ensure that the request headers update with the token as Barrer token I want to avoid any client-side API calls or refetching when navigating between pages. Ideally, I want to keep the enhanced navigation experience provided by nuxt-link without sacrificing SSR-only data fetching. Questions How can I ensure that API calls are always executed on the server side, even during navigation using nuxt-link? Is there a way to disable or prevent client-side refetching while maintaining smooth navigation between pages? Thanks in advance for any help! I'd greatly appreciate any insights, recommendations, or examples from your experience.
2 Replies
kapa.ai
kapa.ai3w ago
Hi @developers_easternts. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To address your concerns about ensuring SSR-only API calls and preventing CSR requests during navigation in Nuxt 3, I'll provide some insights and recommendations based on the available knowledge sources. 1. Ensuring SSR-only API calls: To ensure that API calls are always executed on the server side, even during navigation, you should use the useFetch or useAsyncData composables. These composables are designed to handle data fetching in a way that's compatible with SSR and CSR scenarios. Nuxt 3 Docs: Data Fetching explains: "The useFetch and useAsyncData composables solve this problem by ensuring that if an API call is made on the server, the data is forwarded to the client in the payload." This means that when you use these composables, Nuxt will automatically handle the data fetching on the server and transfer the result to the client, avoiding unnecessary client-side API calls. 2. Preventing CSR requests during navigation: To prevent client-side refetching while maintaining smooth navigation, you can use the getCachedData option with useFetch or useAsyncData. This option allows you to implement custom caching logic. Nuxt 3 Docs: useAsyncData mentions: "getCachedData: Provide a function which returns cached data. A null or undefined return value will trigger a fetch." You can implement a custom caching mechanism to store the fetched data and return it on subsequent navigations, preventing unnecessary API calls. 3. Handling authentication tokens: To ensure that the request headers update with the token as a Bearer token, you can use the useRequestFetch composable. This composable automatically forwards the request context and headers when making server-side fetch requests. Nuxt 3 Docs: useRequestFetch states: "You can use useRequestFetch to forward the request context and headers when making server-side fetch requests." Here's an example of how you can implement these solutions:
<script setup lang="ts">
const authToken = useCookie("Authorization-Token");
const requestFetch = useRequestFetch();

const { data, error } = await useAsyncData(
'yourDataKey',
() => requestFetch('/api/your-endpoint', {
headers: {
'Authorization': `Bearer ${authToken.value}`
}
}),
{
getCachedData: () => {
// Implement your custom caching logic here
// Return cached data if available, or null/undefined to trigger a fetch
}
}
);
</script>
<script setup lang="ts">
const authToken = useCookie("Authorization-Token");
const requestFetch = useRequestFetch();

const { data, error } = await useAsyncData(
'yourDataKey',
() => requestFetch('/api/your-endpoint', {
headers: {
'Authorization': `Bearer ${authToken.value}`
}
}),
{
getCachedData: () => {
// Implement your custom caching logic here
// Return cached data if available, or null/undefined to trigger a fetch
}
}
);
</script>
By using useAsyncData with useRequestFetch and implementing a custom getCachedData function, you can ensure that: 1. API calls are executed on the server side. 2. Authentication tokens are properly included in the request headers. 3. Cached data is used when available, preventing unnecessary refetching. Remember that the useFetch composable is a wrapper around useAsyncData and $fetch, so you can use it as a more convenient alternative if it suits your needs better. These approaches should help you achieve your goals of SSR-only data fetching while maintaining smooth navigation between pages in your Nuxt 3 application. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@1280075996271349796> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?