The invocation of getServerSideProps from nextjs is always missed

I've encountered an issue with my code where I am using prisma to fetch data from my postgreSQL database. The problem lies in the fact that the function getServerSideProps is not being called at all. Even the log message is not being displayed in the console. This file can be found in the 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: One possible explanation could be that in the app router, we are unable to utilize getServerSideProps and other traditional fetching methods for Next.js. Instead, we must convert our components into asynchronous components and perform data fetching within the components. This fetching will take place during server-side rendering. There may be a challenge with an error known as Async Server Component TypeScript Error when assigning types to your functional component.

Answer №1

When working with a page.tsx file, it indicates that you are operating within the next-13 app directory where next.js server-side functions are no longer available.

Previously, next.js would check for the presence of getServerSideProps on a page and execute this function on the server to send content to the browser. However, in the app directory, everything runs fully on the server side.

In your approach, you can still name the function as getServerSideProps, but you will need to manually call it inside the component.

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

Then, within 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} />
    </>
  );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting issue with Next.JS Redux dispatch functionality inside getStaticProps() not functioning as

I have recently started working with Next.JS and decided to integrate Redux into my Next.JS application. I'm facing an issue where my page is supposed to display a list of posts fetched from an API. Everything works fine when I use useEffect() to disp ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

Challenges with rendering Material design tables in React

Task at hand: Display 5 material react tables within 5 different tabs. My current technology stack: "material-react-table": "^2.0.4" "@mui/material": "^5.14.13" "@chakra-ui/react": "^2.4.2" &quo ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

Is it possible to access Next.js API endpoints from another application?

Currently working on building a web application with React on the Next.js framework. I've established an API route that the web app's components retrieve data from. Now, I'm considering developing a mobile app as well - can I utilize the sam ...

Updating the request body in Next 13 with middleware.ts: A step-by-step guide

I am looking for a way to modify the request body in NEXT 13 using a middleware function: import { NextRequest, NextResponse } from 'next/server'; enum MiddlewareRoutes { ACCESS = '/api/access', } const middlewareHandler = async ( ...

What is the method for utilizing array parameters in Prisma?

Is there a way to perform querying similar to this in prisma? http://localhost://3000/api/users?[param1]=[value1]&[param2]=[value2]&...... Alternatively, param1, param2....could be from different models ...

How can I route from a Java backend-generated URL to the reset-password page in Next.js?

Here is the link generated by my Java backend for the user to reset their password: http://127.0.0.1:8080/account/reset/finish?key=vljKlxjYh6Cd2xp119bQ. After clicking on this link, the user will be directed to the reset-password page. The API endpoint for ...

The security rules in Firebase Firestore appear to be completely ineffective

Having just recently started using Firebase, I'm facing some confusion or a potential issue with my Firebase account. After integrating a Firestore Database into my Firebase app, I initially set it up in test mode. According to the documentation I&ap ...

Is the cache option available in the PAGE ROUTER when using the fetch() API in Next.js, similar to the APP ROUTER?

Is the caching behavior of Next.js's fetch API the same in Page Router as it is in App Router? I found information about how it works with App Router here: https://nextjs.org/docs/app/api-reference/functions/fetch. However, I couldn't find any re ...

Seeking assistance with using JavaScript to filter posts from Contentful for a Next.js website

Currently, I am integrating a Next.js blog with Contentful and employing queries to display posts on the homepage. While I can easily use .filter() to feature certain posts based on a boolean value, I am struggling to figure out how to fetch posts that mat ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Tips for resolving the Error: Hydration issue in my code due to the initial UI not matching what was rendered on the server

export default function Page({ data1 }) { const [bookmark, setBookmark] = useState( typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('bookmark')) : [] ); const addToBookmark = (ayatLs) => { s ...

Attention: WARNING regarding the NEXTAUTH_URL in the Development Console

While working on my Next.js web application with next-auth for authentication, I came across a warning message in the development console. The message is related to reloading the environment from the .env.local file and compiling certain modules within the ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

Incorporating MongoDB into a pre-existing Next.js application

Over the weekend, I decided to work on setting up a NextJS app. To get started, I followed the tutorial at: https://nextjs.org/learn/basics/create-nextjs-app?utm_source=next-site&utm_medium=homepage-cta&utm_campaign=next-website Now, I want to add ...

Setting Default Values for Multi-select in React-select Async

What is the method for setting default selected values in React-select Async Multi-select? Below is a sample form utilizing react-hook-form and react-select: <form onSubmit={handleSubmit(onSubmit)} > {updateError && renderError(updateError)} ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...