full stack Nextjs on pages with hono | Sometimes Work, Sometimes Not

I am getting some weird error, once there is some error in my useEffect hook, i get 500 error back in reponse. Then if i again reload the page the whole website with all routes whichever i visit shows 500 error page. It sometimes work,sometimes not this is how my useEffect looks like:
useEffect(() => {
const fetchNews = async () => {
try {
const response = await fetch("/api/news/top");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setDropDownArticles(data as NewsData);
const article_list: topArticle[] = [];

Object.keys(data as NewsData).forEach((category) => {
(data as any)[category].slice(0, 2).forEach((items: Article) => {
const item: topArticle = {
title: items.title,
image_url: items.image_url,
};
article_list.push(item);
});
});

setTopArticles(article_list);
} catch (error) {
console.error("Error fetching news: ", error);
}
};

fetchNews();
}, []);
useEffect(() => {
const fetchNews = async () => {
try {
const response = await fetch("/api/news/top");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setDropDownArticles(data as NewsData);
const article_list: topArticle[] = [];

Object.keys(data as NewsData).forEach((category) => {
(data as any)[category].slice(0, 2).forEach((items: Article) => {
const item: topArticle = {
title: items.title,
image_url: items.image_url,
};
article_list.push(item);
});
});

setTopArticles(article_list);
} catch (error) {
console.error("Error fetching news: ", error);
}
};

fetchNews();
}, []);
Here is my /api file
app.get("/news/top", async (ctx) => {
try {
const { KV } = getRequestContext().env;

const keys = ["business", "politics", "sports", "tech", "business"]; // Changed the last key to "top"
const promises = keys.map((key) => KV.get(key));

const [business_news, politics_news, sports_news, tech_news, top_news] =
await Promise.all(promises);

const news = {
business: JSON.parse(business_news || "null"),
politics: JSON.parse(politics_news || "null"),
sports: JSON.parse(sports_news || "null"),
tech: JSON.parse(tech_news || "null"),
top: JSON.parse(top_news || "null"),
};

return ctx.json(news);
} catch (error) {
console.error("error: ", error);
return ctx.json({ message: "Internal server error" });
}
});
app.get("/news/top", async (ctx) => {
try {
const { KV } = getRequestContext().env;

const keys = ["business", "politics", "sports", "tech", "business"]; // Changed the last key to "top"
const promises = keys.map((key) => KV.get(key));

const [business_news, politics_news, sports_news, tech_news, top_news] =
await Promise.all(promises);

const news = {
business: JSON.parse(business_news || "null"),
politics: JSON.parse(politics_news || "null"),
sports: JSON.parse(sports_news || "null"),
tech: JSON.parse(tech_news || "null"),
top: JSON.parse(top_news || "null"),
};

return ctx.json(news);
} catch (error) {
console.error("error: ", error);
return ctx.json({ message: "Internal server error" });
}
});
No description
8 Replies
thomasgauvin
thomasgauvin7mo ago
Are you sure this is related to the /api/news/top request? UseEffect is a client side hook, so should be executed on the server and shouldn't be responsible for this internal server error Are you using Next on pages?
Mrinank
MrinankOP7mo ago
yes I am using next on pages. but ig problem is with KV, i also tried using KV api, its working in localhost but not in production.
app.get("/news/top", async (ctx) => {
const { CF_ACCOUNT_ID, KV_API_TOKEN, KV_NAMESPACE_ID } = env(ctx);
try {
const keys = ["business", "politics", "sports", "tech", "top"];
const promises = keys.map((key) =>
fetch(
`https://api.cloudflare.com/client/v4/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${KV_NAMESPACE_ID}/values/${key}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${KV_API_TOKEN}`,
"Content-Type": "application/json",
},
}
).then((res) => res.json())
);
const [business_news, politics_news, sports_news, tech_news, top_news] =
await Promise.all(promises);
const news = {
business: business_news,
politics: politics_news,
sports: sports_news,
tech: tech_news,
top: top_news,
};
//console.log(news); // Print the news object to the console
return ctx.json(news);
}
app.get("/news/top", async (ctx) => {
const { CF_ACCOUNT_ID, KV_API_TOKEN, KV_NAMESPACE_ID } = env(ctx);
try {
const keys = ["business", "politics", "sports", "tech", "top"];
const promises = keys.map((key) =>
fetch(
`https://api.cloudflare.com/client/v4/accounts/${CF_ACCOUNT_ID}/storage/kv/namespaces/${KV_NAMESPACE_ID}/values/${key}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${KV_API_TOKEN}`,
"Content-Type": "application/json",
},
}
).then((res) => res.json())
);
const [business_news, politics_news, sports_news, tech_news, top_news] =
await Promise.all(promises);
const news = {
business: business_news,
politics: politics_news,
sports: sports_news,
tech: tech_news,
top: top_news,
};
//console.log(news); // Print the news object to the console
return ctx.json(news);
}
Also when some internal server error happens ,and that default black 500 page comes,the whole website becomes unavailable for that browser,, every route then starts showing that black page
thomasgauvin
thomasgauvin7mo ago
Might be something related to your configuration of your env variables in production? If it's working locally, the KV seems to be accessible, so are you sure you can get the right ctx from your API handler?
Mrinank
MrinankOP7mo ago
I tested this also but nothing worked
import { getRequestContext } from "@cloudflare/next-on-pages";

const { CF_ACCOUNT_ID, KV_API_TOKEN, KV_NAMESPACE_ID } =
getRequestContext().env;
import { getRequestContext } from "@cloudflare/next-on-pages";

const { CF_ACCOUNT_ID, KV_API_TOKEN, KV_NAMESPACE_ID } =
getRequestContext().env;
i think the api routes dont work sometimes in next on pages
thomasgauvin
thomasgauvin7mo ago
Hmm yep, seems Next.js related, any chance you can provide a repro? I'm not as familiar with Next-on-pages intricacies, might be more helpful for @Greg Brimble | Cloudflare and/or to submit to https://github.com/cloudflare/next-on-pages
GitHub
GitHub - cloudflare/next-on-pages: CLI to build and develop Next.js...
CLI to build and develop Next.js apps for Cloudflare Pages - cloudflare/next-on-pages
Mrinank
MrinankOP7mo ago
Repo link: https://github.com/Mrinank-Bhowmick/streaklens Live URL : https://streaklens.mrinank.me (frontend: vercel, backend: worker) Actually sometimes its working, sometimes its not. Thats the main problem, after too much trial and error i guess sometimes internal api routes calling dont work like this:
router.push(`/ideator/c/${chatID}`);
router.push(`/ideator/c/${chatID}`);
But fetching outside URL always works:
const response = await fetch(
"https://topnews.bhowmickmrinank.workers.dev/"
);

const response = await fetch(
"https://topnews.bhowmickmrinank.workers.dev/"
);

and one more wired thing I observed that if in any case the user gets 500 internal server error , the whole website with all the routes starts showing 500 internal server error
Mrinank
MrinankOP7mo ago
@Better James Repo link: https://github.com/Mrinank-Bhowmick/streaklens Live URL : https://streaklens.mrinank.me/ (frontend: vercel, backend: worker)
GitHub
GitHub - Mrinank-Bhowmick/streaklens: AI Platform for Content Creators
AI Platform for Content Creators. Contribute to Mrinank-Bhowmick/streaklens development by creating an account on GitHub.
StreakLens
AI Platform for Content Creators
Nob
Nob7mo ago
@Mrinank Hey i had a similar problem and fixed it by downgrading next to version 14.1.3. Let me know if that fixed it for you
Want results from more Discord servers?
Add your server