Api route returns Fetch Failed

Hey, I have an api route that returns some posts, it works when I navigate to it, but when I try to request it using a RSC, it throws a Fetch Failed error, export
async function getNews() {
const res = await fetch(`${env.NEXT_PUBLIC_APP_URL}/api/news`);
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}
async function getNews() {
const res = await fetch(`${env.NEXT_PUBLIC_APP_URL}/api/news`);
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}
export async function GET(req: Request) {
const allPosts: Post[] = await db.select().from(posts);
return NextResponse.json(allPosts, { status: 200 });
}
export async function GET(req: Request) {
const allPosts: Post[] = await db.select().from(posts);
return NextResponse.json(allPosts, { status: 200 });
}
export default async function News() {
const news: Post[] = await getNews();
console.log(news);
return (
<div>
<h1>News</h1>
</div>
);
}
export default async function News() {
const news: Post[] = await getNews();
console.log(news);
return (
<div>
<h1>News</h1>
</div>
);
}
2 Replies
Alan Ibarra-2310
Alan Ibarra-231016mo ago
There might be an issue with the environment variable, prefixing it with NEXT_PUBLIC, I think it makes it only accessible on the client and not on the server. So, when you invoke getNews from an RSC its running in the context of the server. You could verify this is you run the function from within a useEffect or event handler. https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
Configuring: Environment Variables
Learn to add and access environment variables in your Next.js application.
max14
max1416mo ago
ahhh ok yes I think that’s it
Want results from more Discord servers?
Add your server