Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
getServerSideProps does not fetch the data at first time in Nextjs

I have a component that fetch data from my MongoDB database.After fetching the data, I want to create some cards by this data. My backend server is working. Also I connect my frontend to backend.

import axios from "axios";
import Cards from "../components/Cards";
import CarouselComponent from "../components/Carousel";
import { Navbar } from "../components/Navbar";

export default function Home({ products }) {
  console.log(products);
  return (
    <div className="">
      <Navbar />
      <CarouselComponent />
      {/* <Cards products={products} /> */}
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`http://localhost:3000/api/products`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { products: data } };
}


enter image description here products prop is turns me empty object. But when I refresh the page second time, it brings me all the products. I tested it in postman, also in postman I can get all the products. Why when I stop the server and start it again it doesn't fetch the products?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

SOLUTION I added

 await dbConnect();

to

export async function getServerSideProps() {
  // Fetch data from external API
  await dbConnect();
  const res = await fetch(`http://localhost:3000/api/products`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { products: data } };
}

I think my mistake was to try fetching data before connecting to server

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!