Encountering "Error: fetch failed" in Strapi 5

I am trying to fetch a list of blog posts from my Strapi backend and I’m getting a “Error: fetch failed” error. I’ve tried every solution I could find online and none has worked.

Below is the code of blog/page.tsx page


import React from 'react'

async function getPosts(){
  const baseURL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:1337";
  const path = "/api/blog-posts";

  const url = new URL(path, baseURL);

  const res = await fetch(url);
  if(!res.ok) throw new Error("Failed to fetch blog posts");

  const data = await res.json();
  console.log(data);

  return data;
}

async function BlogPage() {
  const blogPosts = await getPosts();
  console.log(blogPosts);
  return (
    <div>BlogPage</div>
  )
}

export default BlogPage

Is this related to Strapi 5 or am I missing something?

This topic has been created from a Discord post (1299205931313397931) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord

Have you gave your API appropriate permission to access blog data?
You can navigate to the **Roles **section in Settings / **Users & Permission **Plugin page, select the **Public **role, and click on the **Blogs **permission.

Yes, I have given my API the appropriate permissions

What value does your API return?
You can simply get the response by navigating to http://localhost:1337/api/blog-posts on your browser.

Here’s the image of my API response

I used Postman and it worked

hmm, I guess you used wrong port 1377instead of 1337.

I changed to 1337 and it’s still not working

is there any configuration I’m suppose to do?

I have solved the issue, I guess

I changed localhost to 127.0.0.1

I’m not sure why localhost is not accessible while 127.0.0.1 is working. Have you reviewed hosts file on your local machine?

how do I do that?

Windows: c:\Windows\System32\Drivers\etc\hosts
Mac: sudo nano /etc/hosts

I’m getting directory name is valid error