Struggling with NextJS? The error message "getServerSideProps" is not compatible with the app/ directory

Having trouble copying and pasting the official examples from NextJS for getServerSideProps? Errors keep popping up:

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getServerSideProps: GetServerSideProps<{
  repo: Repo
}> = async () => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  return { props: { repo } }
}
 
export default function Page({
  repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return repo.stargazers_count
}

Error:

./app/page.tsx
ReactServerComponentsError:

"getServerSideProps" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching

The error message directs you to the data-fetching documentation which led to this problem.

Steps to reproduce:

  1. Create the app:

    npx create-next-app@latest

    (TypeScript: yes, AppRouter: yes, src-directory: no)

  2. Change the pages.tsx into the variant above from the Docs.

package.json:

  "scripts": {
    "dev": "next dev -p 8002",
    "build": "next build",
    "start": "next start -p 8002",
    "lint": "next lint"
  },
  "dependencies": {
    "@types/node": "20.4.2",
    "@types/react": "18.2.15",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.14",
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.10",
    "eslint-config-prettier": "^8.8.0",
    "eslint-plugin-prettier": "^5.0.0",
    "next": "13.4.10",
    "postcss": "8.4.26",
    "prettier": "^3.0.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "tailwindcss": "3.3.3",
    "typescript": "5.1.6"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^6.1.0"
  }

Need help resolving this issue and understanding how to use getServerSideProps with AppRouter?

Answer №1

If you are utilizing the app router, it is not possible to employ getServerSideProps. Be sure to refer to the documentation for information on fetching data using components in the app directory.

Answer №2

To utilize the getServerSideProps feature, it is necessary for your component to reside in the /pages directory. I restructured your example as follows and managed to make it function:

my-app/
├─ node_modules/
├─ app/
│  ├─ globals.css
│  ├─ layout.tsx
├─ .gitignore
├─ package.json
├─ README.md
├─ pages/
│  ├─ index.tsx

By relocating your code there, you will resolve the issue. This requirement stems from the special treatment of components within the /pages directory. For further information, you can refer to this documentation. In brief, Next automatically manages routing based on the pages directory and executes server-side logic prior to delivering your page. Attempting this with a non-page component would be ineffective since those are loaded after the initial page load (i.e., not server-side rendered)

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

Which rxjs operator should be used when dealing with nested subscriptions in the presence of an if statement?

In my Angular/Typescript project, I am dealing with 2 subscriptions. Each subscription is subscribing to its own observable A and B, which are located outside the component in the service file. Sometimes, when A changes, B may or may not change based on c ...

Encountering Excessive Open Files Error with NextJS Deployment

I'm encountering a challenge in my Production environment during peak traffic hours. Any assistance with pinpointing the origin of this issue would be greatly appreciated. Error logs - [Error: EMFILE: too many open files, open '/app/.next/static ...

What limitations prevent me from utilizing a switch statement to refine class types in Typescript?

Unique Playground Link with Comments This is a standard illustration of type narrowing through the use of interfaces. // Defining 2 types of entities enum EntityType { ANIMAL = 'ANIMAL', PLANT = 'PLANT', } // The interface for ani ...

Is there a method in Typescript to constrain an exported function's accessibility so that it is only importable by specific files?

I would like developers to use a class or interface instead of directly importing functions. Is there a way to restrict so only the class can import the function? I prefer not to consolidate all the functions in a single file, especially in a large proje ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

What is the best way to test an oclif CLI tool that interacts with a Rest API

How can I efficiently test the TypeScript code I've written for an Oclif CLI that interacts with a Node.js and Express.js REST API? I'm currently using Mocha/Chai for testing, but I'm struggling with testing the specific command code from my ...

Is there a way to track all Angular form controls that have switched between being enabled and disabled?

Summary: When a FormGroup contains a nested FormControl that changes from disabled to enabled or vice versa, the FormGroup is not marked as dirty. Details: How can you identify all form controls within a FormGroup that have switched between being enabled ...

Quick method to alter theme and store it - Ionic

How can I modify the appearance of an element by changing its color and font size when a user clicks a button? <h1> Hello Stackoverflow </h1> <button (click)="changeTheme()">Change Theme</button> What is the best approach to chang ...

Matching a buffer request body with Mock Service Worker: Step-by-step guide

Currently, I am utilizing Nock, but I'm interested in switching to Mock Service Worker. Using Nock, I can match the stringified request body with a specified buffer: const request = nock(hostname) .post('/api/instance', Buffer.from ...

Change rem into a whole number

How can I convert a rem value to an integer? The code snippet this.props.viewTitleContainerStyle.paddingTop returns a value of 1.00rem in the debugger. The viewTitleContainerStyle is stored as theme.sizes.Measures.Measure100. I need to convert this to an ...

A guide on using MDX with MUI (NextJS) to style various components like <ol> using the <Typography> component

Is there a method to apply MUI theme styles to different MDX elements such as ol or li? Currently, the MDX output is unstyled HTML; <ol> <li>One</li> </ol> While MUI does provide a <List> component, I simply want the font ...

NG01203: The form control with the name 'name' does not have a specified value accessor

This question was originally posted by JOYBOY but was later deleted. The title of the question was NG01203: No value accessor for form control name: 'name' In my Angular 18 application, I am utilizing both standalone components and module-based ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

"Jesting with JavaScript: Thou shall be warned, for undefined does

While running my unit tests with jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Can anyone provide suggestions on how to properly test the following line using jest? [videoTrack] = (await ...

Tips for transferring data from one component to another component

Recently, I've been struggling to transfer data between components in my Angular project. Despite trying numerous online examples, none have seemed to work for me. Most of the tutorials I came across suggest using @Input and @Output as the ideal way ...

Utilizing Djoser in Django Rest Framework to bypass Facebook and Google authentication, integrated with Next.js+React for a seamless frontend experience

My approach involved using Djoser to manage essential user authentication functionalities in Django Rest Framework. To explore its social auth endpoint, I referred to its documentation for guidance. Initially, I incorporated a redirect_uri into the endpoin ...

Attempting to get Angular's dependency injection functioning properly

My Angular dependencies seem to be causing issues and I'm not sure why. All the guides I've checked suggest that this should work: import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @ ...

Navigating through pages: How can I retrieve the current page value for implementing next and previous functions in Angular 7?

Greetings, I am a new learner of Angular and currently working on custom pagination. However, I am facing difficulty in finding the current page for implementing the next and previous functions. Can anyone guide me on how to obtain the current page value? ...

Consistently encountering null sessions with NextJS next-auth get session

Having trouble retrieving session data when using getSession({req}) in an API call? However, useSession() is working fine within a component. Package versions: [email protected], [email protected] Issue: api/lists.ts: import prisma from ". ...