So if I have a simple static page to be generated ideally at build time, so that is faster to load frontend, SEO is great, but to populate it I need data from an external API, like Strapi for instance, what's the best way to proceed with the new Next.js 13.4?
In Next.js 12 I'd create a getStaticProps
and pass the data as props to my page.
But when it comes to Next.js 13.4, documentation says to do this: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#async-and-await-in-server-components
which looks exactly the same as my page.js:
async function getData() {
const res = await fetch(`${process.env.MY_STRAPI_URL}/api/works`);
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Home() {
const works = await getData();
return (
<main className="flex min-h-screen flex-col items-center justify-between p-5">
<div>
{works && works?.data.map((item, i) => (
<div key={i}>
{item.attributes.Title}
</div>
))}
</div>
</main>
)
}
so why is this throwing
error TypeError: fetch failed
the api ${process.env.MY_STRAPI_URL}/api/works
loads correctly when I try in the browser.
EDIT: a try catch error shows as:
TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11118:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: connect ECONNREFUSED ::1:1337
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 1337
}
}
it looks like Next.js is trying to use IPv6 ?
SOLVED: using 127.0.0.1 instead of localhost in the MY_STRAPI_URL env.