Search code examples
vue.jsnuxt.jsstrapi

Unable to correctly retrieve API objects


I recently started using the @nuxtjs/strapi package with Strapi 4 and Nuxt 3. I find this module lacking in documentation as I'm not sure how to retrieve the information from my API. Here's what I've done so far:

const { find } = useStrapi()
const url = useStrapiUrl();
let kitUrl = '';
const { data, pending, refresh, error } = await useAsyncData(
    'home-page',
    () => find('home-page', { populate: ['kit_de_presse'] })
)
const response = data?.value?.data;
kitUrl = url + response?.attributes;

A number of problems arise: The first is that every time I reload a page, I get an undefined, unlike if I modify the code and vite let a hot reload take place. The second is that I'm retrieving a complex "RefImpl" object, as opposed to calling find() on its own without usingAsyncData().

How am I supposed to retrieve my object?


Solution

  • When using useFetch or useAsyncData with Nuxt, the request is executed both server-side and client-side. My application called an API on localhost which ran on a Docker container, just like my application. When the client calls the API, everything works, since the container port is shared with my host machine. But when the server calls it, it calls it from inside its container, so localhost is itself. The solution was to create a custom network on the docker-compose and to check before making the request on which URL to make it:

    docker-compose.yml:

    networks:
      Strapi:
        driver: bridge
    

    Create a new custom function on Nuxt app:

    export async function fetchStrapiUrl(url: string) {
        const runtimeConfig = useRuntimeConfig()
        const strapiBaseUri = process.server ? "http://strapi:1337/api" : runtimeConfig.public.strapiBaseUri + '/api';
        const res = await fetch(strapiBaseUri + url);
        return await res.json();
    }
    

    nuxt.config.ts:

    runtimeConfig: {
            public: {
                strapiBaseUri: process.env.NODE_ENV === "production" ? "https://preprod.redacted.com:1338" : "http://localhost:1337"
            }
        }