skip to Main Content

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/

Link

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


  1. Chosen as BEST ANSWER

    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

    import {connect} from "@/dbConnection/dbConnection";
    import Post from "@/modals/postModal";
    
    // Get all posts
    
    async function handler (request) {
        console.log('Request Made on Get Posts...' );
        const newHeaders = new Headers(request.headers);
        newHeaders.set('Cache-Control', 'no-cache');
    
        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"});
    
        }
    }
    
    
    
    export {handler as GET}
    

    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.


  2. 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.length === 0) {
            return Response.status(404).json({ error: "Posts not found" });
        }
        return Response.status(200).json({ posts });
    } catch (e) {
        console.error(e);
        return Response.status(500).json({ error: "Database error" });
    }
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search