I'm encountering a persistent issue with my Next.js application deployed on Vercel. Upon the initial request to the "/api/prompt" endpoint, I consistently receive a 500 Internal Server Error. Notably, subsequent reloads work without any problems. When I run the app on localhost it works fine as well.
Upon reviewing the Vercel logs, I noticed that the "MongoDB connected" log entry appears only after the 500 server error, suggesting a possible delay in establishing the MongoDB connection.
Key code snippets:
/utils/database.tsx:
import mongoose from "mongoose";
let isConnected = false;
export const connectToDB = async () => {
mongoose.set("strictQuery", true);
if (isConnected) {
console.log("MongoDB is already connected");
return true;
}
try {
await mongoose.connect(process.env.MONGODB_URI!, {
dbName: "share_funfact"
});
isConnected = true;
console.log("MongoDB connected")
return true;
} catch (error) {
console.log(error);
}
}
/app/api/prompt.tsx:
import { connectToDB } from "@utils/database";
import Prompt from "@models/prompt";
export const dynamic = "force-dynamic";
export const GET = async (request: any) => {
try {
await connectToDB();
const prompts = await Prompt.find({}).populate("creator");
return new Response(JSON.stringify(prompts), { status: 200 });
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 });
}
};
/app/components/feed.tsx:
"use client";
import { useState, useEffect } from "react";
const Feed = () => {
...other code
useEffect(() => {
const fetchPosts = async () => {
const response = await fetch("/api/prompt");
if (response) {
const data = await response.json();
setPosts(data);
}
};
fetchPosts();
}, []);
return (
<section className="feed">
<form className="relative w-full flex-center">
<input
type="text"
placeholder="Search for a tag or a username"
value={searchText}
onChange={handleSearchChange}
required
className="search_input peer"
/>
</form>
{searchText ? (
<PromptCardList
data={searchedResults}
handleTagClick={handleTagClick}
/>
) : (
<PromptCardList data={posts} handleTagClick={handleTagClick} />
)}
</section>
);
};
export default Feed;
Despite my attempts to solve the problem, the issue persists. Seeking guidance on troubleshooting steps and potential solutions to resolve this 500 Internal Server Error. Any insights are highly appreciated. You can find the whole repo with alle the code on my Github.
Thank you!