next.jsstatic-site-generation

Data is not fetching properly in SSG Next.js


While creating the post (for the blog) using Jodit Editor, I used to directly save it's output (html string) into mongo.

Then after adding SSG, at the build time, the (consoled) fetched data appears as this.

Whereas simply fetching the api shows data correctly. here

Code of getStaticProps & getStaticPaths


export async function getStaticProps({ params }) {
    try {
        const { data } = await axios.post(baseUrl + getPostBySlug, { slug: params?.slug });

        console.log({ slug: params?.slug }, 'data 2 ->', data);    // here is the data consoled

        return {
            props: { post: data?.data ?? null },
            revalidate: 10,
        }
    }
    catch (err) {
        return {
            props: { post: null },
            revalidate: 10,
        }
    }
}

export async function getStaticPaths() {
    try {
        const res = await fetch(baseUrl + getAllPosts, { method: 'GET' });
        const data = await res?.json();

        if (data?.success && data?.data) {
            return {
                paths: data?.data?.map(({ slug }) => ({ params: { slug } })),
                fallback: true,
            }
        }
        else {
            return {
                paths: [{ params: { slug: '/' } }],
                fallback: true,
            }
        }
    }
    catch (err) {
        return {
            paths: [{ params: { slug: '/' } }],
            fallback: true,
        }
    }
}

Final output, a SSG page but with no data init -> here


Solution

  • You need to update to Axios ^1.2.1 - there was an issue with previous versions.

    You can set the headers as a temporary solution to prevent this from happening.

    await axios.post("your/api/url",{
     headers: { Accept: 'application/json', 'Accept-Encoding': 'identity' },
     { slug: "url-slug" }
    )