I’m encountering an issue with fetching data from my database in a production environment. The code works perfectly fine on localhost, but when deployed to production, it fails to retrieve updated data. Here’s the relevant code snippet:
import {connect} from "@/dbConnection/dbConnection";
import Post from "@/modals/postModal";
export const GET = async () => {
console.log('Request Made on Get Posts...' );
try{
await connect();
const posts = await Post.find().sort({createdAt: -1}).limit(20);
if(!posts){
return Response.json({error: "Posts not found"});
}
return Response.json({posts});
}catch (e) {
return Response.json({error: "Database error"});
}
}
Code for fetching data :
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true)
setTimeout(
() => {
fetchPosts().then((r) => {
setPosts(r.posts)
setLoading(false)
}).catch((e) => {
setError("Error fetching posts")
setLoading(false)
});
}
, 2000
)
}
, []);
async function fetchPosts() {
try {
const response = await axios.get('/api/post/getblogs');
return response.data;
} catch (error) {
setError("Error fetching posts")
}
}
Link of production : https://blogging-website-nextjs-blue.vercel.app/
Steps taken:
Checked database connection configuration, which seems correct.
Tested the code in localhost, where it works perfectly.
Reviewed logs for any errors or warnings, but found none related to this issue.
Expected behavior:
When a request is made to fetch posts, the code should retrieve the latest data from the database
2
Answers
The root cause of the problem was, the browser might have been caching the response from the backend route, leading to the same data being served on subsequent requests without hitting the server again.
New Code
By setting the Cache-Control header to no-cache, the browser is instructed not to cache the response, ensuring that fresh data is fetched from the server each time the endpoint is accessed.
}