Using TypeScript with Next.js getStaticProps causes errors

Currently, I am grappling with utilizing getStaticProps along with TypeScript. Initially, I attempted to achieve this using a function declaration:

import { Movie } from './movies/movie'
import { GetStaticProps } from 'next'

export async function getStaticProps(): GetStaticProps {
    const res = await fetch('https://my-json-server.typicode.com/horizon-code-academy/fake-movies-api/movies');
    const movies: Movie[] = await res.json()

    return {
        props: { movies }
    };
}

However, while doing so, an error arose stating: Type '{ props: { movies: Movie[]; };' is not assignable to type 'GetStaticProps'

I experimented with alternative types such as

GetStaticProps<{ movies: Movie[] } >
and
Promise<GetStaticProps<{ movies: Movie[] } >>
, but unfortunately, none of them seemed to work. The incorrect return value persisted. Upon delving into answers on Stackoverflow, it became evident that many approaches involve utilizing arrow functions for this purpose. So, I also tried:

export const getStaticProps: GetStaticProps = async () => {
    const res = await fetch('https://my-json-server.typicode.com/horizon-code-academy/fake-movies-api/movies');
    const movies: Movie[] = await res.json()

    return {
        props: { movies }
    };
}

Regrettably, my attempt to use arrow functions was unsuccessful, as I encountered the error: "getStaticProps" is not a valid Next.js entry export value.

If you have any insightful suggestions or solutions, they would be greatly appreciated!

Answer №1

The issue I encountered stemmed from the fact that my component was located within the app folder instead of the necessary pages folder at the root level for getStaticProps to function correctly. My confusion arose from my lack of awareness regarding the new App Router approach used in Next.js applications, leading me to mix outdated practices with current ones. Following an outdated tutorial from two years ago, I unknowingly opted for app routing during app creation, resulting in the creation of the app folder instead of the required pages folder. It appears that the modern approach no longer utilizes getStaticProps. For more details, visit: https://nextjs.org/docs/pages/building-your-application/upgrading/app-router-migration

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

BarChart is failing to exhibit data in tooltips when using dynamic keys

Query Description Hello! I'm currently tackling an issue with a bar chart. Everything is working smoothly, except for the default tooltip, which appears blank when hovering over the bars. My chart utilizes dynamic keys for the legends, and they are f ...

Sending data between components in Angular can be achieved by using various methods. One common approach is to utilize

I am encountering an issue with a component named customers.component Below is the code from the customers.component.ts file: @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./cu ...

"Save this HTML code snippet to easily copy an anchor tag with an attached href

For my latest personal project, I'm developing a URL shortening tool that includes a feature to copy both the shortened URL and its hyperlink with just one click. The core functionality of URL shortening is managed through Formik and Yup libraries, w ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

Tips for sending custom props to a dynamic page in Next.js

I have created a component called Card.js which is responsible for linking to dynamic pages when a card is clicked. My goal is to pass a value, such as 'category', to the dynamic page [id].js so that I can implement additional logic there. Card. ...

Struggling to utilize a custom react-three-fiber component despite specifying the custom type within the react-three-fiber module

Currently developing a react application focused on visualizing mathematical concepts with the help of react-three-fiber. Utilizing TypeScript, I discovered that by extending custom ThreeElements (https://docs.pmnd.rs/react-three-fiber/tutorials/typescript ...

Is it possible to customize the naming of the many-to-many tables in Next.js with Prisma?

Prisma automatically generates names for many-to-many tables, such as "_TableaToTableb" combining the names of Table A and Table B. The default id field names inside these tables are "A" and "B". I have two questions: Can I manually name the relation ta ...

Build Folder not being generated in Next Js version 13.5.6

I'm running into an issue where I am unable to generate the build folder in Next.js 13.5 using npm run build. Additionally, I need to upload this dynamic Next.js project to GoDaddy cpanel. Can anyone help? Thanks! ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

Utilize the React.createContext() method integrated within the _app.js file

I need to retrieve the emailLogin function from my context in a different component: userContext.js import React, { useEffect, useState } from 'react'; import cookie from 'js-cookie'; import {firebase} from './firebase-client&apos ...

Unable to programmatically uncheck a checkbox after it has been manually checked: Angular

After being selected through the UI by clicking on the checkbox, I am encountering an issue where I cannot unselect the checkbox programmatically. To see this behavior in action, visit the sample app, where you can click on the checkbox to select it and t ...

Retrieve HTML form data or an object within the getServerSideProps() function in NEXTJS

How can I submit form data from a NextJS page to another page with server-side rendering? The function getServerSideProps() on the receiving page requires these form data to make an API call. I considered using localStorage/sessionStorage to store the da ...

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...

`The process of converting Typescript to ES5 through compiling/transpiling is encountering issues`

My current project involves using Webpack and integrating angular2 into the mix. To achieve this, I made adjustments to my setup in order to compile TypeScript. Following a resource I found here, my plan was to first compile TypeScript to ES6 and then tra ...

What is the return type of the Array.prototype.sort() method in Typescript?

I have created a custom type for arrays that are considered "sorted" like this: type Sorted<T> = T[]; This serves as a reminder for developers to provide a sorted array of any type and ensure the sorting themselves. Although I understand that Types ...

Unable to retrieve images from the public directory, yet all other content on the page functions flawlessly

The images on my website are not loading and are displaying an internal server error message An issue with the Clerk authentication process is causing the following error to occur: ⨯ Error: Clerk: auth() was called but Clerk cannot detect usage of authM ...

Issue with decorators not functioning in the latest alpha version of Sequelize v7

As I was exploring sequelize v7 (alpha), I encountered multiple errors when trying out basic examples directly from their documentation. For instance, taken straight from the official documentation import { Sequelize, DataTypes, Model, InferAttributes, Inf ...

Juicer- Setting restrictions on the frequency of posts

How can I limit the number of posts displayed using the react-juicer-feed component? import { Feed } from 'react-juicer-feed'; const MyFeed = () => { return ( <Feed feedId="<feed-id>" perPage={3} /> ...