Search code examples
next.jsserver-side-renderingprismanext.js13getserversideprops

getServerSideProps from nextjs is never invoked


That is my code. I use prisma for fetching data from my postgreSQL db. The problem is that getServerSideProps is never invoked. The log message is not even printed in a console. The file is located in app folder

*page.tsx*

import Header from "./HomePageComponents/Header/Header";
import RestaurantCards from "./HomePageComponents/RestaurantCards/RestaurantCards";
import { PrismaClient } from "@prisma/client";
import { NextPage } from "next";

export const getServerSideProps = async () => {
  const prisma = new PrismaClient();
  const restaurants = await prisma.restaurant.findMany();
  console.log("Logging: ", restaurants);
  return { props: { restaurants } };
};

const Home: NextPage<any> = (props) => {
  return (
    <>
      <Header />
      <RestaurantCards />
    </>
  );
};

export default Home;

Edit 1: The possible answer is that in the app router we can't use getServerSideProps and other traditional for nextjs fetching methods. Instead, we have to turn our components into async components and fetch data inside of the components. Fetching will occur during server-side rendering. A problem may occur with as called Async Server Component TypeScript Error during assigning types to your functional component.


Solution

  • Since you have page.tsx, you are most likely in next-13 app directory where we no longer have next.js server-side functions.

    Before, next.js used to check if there is getServerSideProps on the page, and if there is, next.js used to execute this function on the server and ship the content to the browser. in app directory, we are fully on the server.

    In your implementaion, you could still name the function as getServerSideProps but then you need to call it manually inside the component.

        const getServerSideProps = async () => {
          const prisma = new PrismaClient();
          const restaurants = await prisma.restaurant.findMany();
          return restaurants;
        };
    

    Then inside the component:

        // I defined the component as async so that I could await the getServerSideProps
        const Home: NextPage<any> =async  (props) => {
          const restaurants=await getServerSideProps()
          return (
            <>
              <Header />
              // you probably need to pass the restaurants to this component
              <RestaurantCards restaurants={restaurants} />
            </>
          );
        };