Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build.

FetchError: request to http://localhost:3000/api/cs failed,
reason: connect ECONNREFUSED 127.0.0.1:3000

After researching on GitHub, I learned that using fetch directly in getStaticProps is not recommended. To address this issue, I refactored my code by moving the fetch logic into a separate file and calling the function inside the getStaticProps method. Here's how the updated code looks:

export async function getStaticProps({ params }) {
  const data = await getData(params.id);

  return {
    props: {
      data,
    },
  };
}
export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: "cs" } },
      { params: { id: "hyd" } },
      { params: { id: "cass" } },
    ],
    fallback: false,
  };
}

The actual fetch logic for getData resides in another file:

export async function getData(id){
    const res = await fetch(`http://localhost:3000/api/${id}`)
    const data = await res.json()

    return data
}

Although this code functions correctly in local development, it encounters errors during next build due to the server being unavailable in build mode. To resolve this, I ran the server in a separate terminal, which led to an error with the WriteStream instance.

Error: EPERM: operation not permitted, open 'D:\next-project\next-website\.next\trace'
Emitted 'error' event on WriteStream instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)    
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4048,
  code: 'EPERM',
  syscall: 'open',
  path: 'D:\\next-project\\next-website\\.next\\trace' 
}

While I can successfully fetch data from the client side, I wanted to explore utilizing getStaticProps as there are only a few pages in my project. What is the correct approach to fetch the local Next.js API for building a static page?

Edit: adding API endpoint file: api/cs

export default async function handler(req, res) {
  res.status(200).json({
    headerText:
      "Page Header text",
    joinText:
      "Some text",
    benefits: [
      {
        src: "/cs/photo-1.webp",
        text: "Some text",
      },
      {
        src: "/cs/photo-2.webp",
        text: "some text",
      },

    ],
    advisor: {
      name: "Name",
      email: "person-email",
      linkedin: "https://www.linkedin.com/in/person",
    },
    advisorMsg:
      "Some text",
  });
}

Answer №1

Avoid calling an API Route from getStaticProps or getStaticPaths. It is recommended not to fetch an API Route from these functions. Instead, it is advised to write your server-side logic directly within getStaticProps or getStaticPaths (or utilize a helper function).

The reason for this recommendation is that getStaticProps and getStaticPaths are executed only on the server-side and not on the client-side. Additionally, these functions are not bundled with the JavaScript code sent to the browser. This allows you to include sensitive operations like database queries without exposing them to clients. Refer to the Writing Server-Side Code documentation for more information.

https://nextjs.org/learn/basics/api-routes/api-routes-details

Therefore, refrain from fetching data from the local API route in the getData function. Retrieve the data from the source where the API route itself fetches it.

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

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

Sliding through HTML content

Unfortunately, I lack expertise in advanced HTML and CSS. After some investigation, I attempted to create a "content slider" similar to the one on the Redlight Traffic website (an anti-human trafficking organization). However, my efforts have been unsucces ...

Is there a way to display the background when the popover is visible and hide it when the popover is hidden?

How do I make the backdrop appear when the popover is displayed, and disappear when the popover is closed? $(function(){ var content = '<button class="btn btn-sm btn-default" onclick="location.href=\'/billing/\'">Pay Now ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

The lower section of the scrollbar is not visible

Whenever the vertical scroll bar appears on my website, the bottom half of it seems to be missing. For a live demonstration, you can visit the site HERE (navigate to the "FURTHER READING" tab). HTML: <!DOCTYPE html> <html lang="en"> <h ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Exploring uncharted territory with the Navigator component in React Native

I am experiencing an issue with undefined navigator when using React Native MessageTabs: _onPressItem = (item) => { const { navigate } = this.props.navigation; //console.log(JSON.stringify(item)); navigate('SingleConversation', {id ...

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Exploring the orderBy feature in the react-firebase-hooks library with NextJS

Recently, I've been utilizing the React Firebase Hooks package from this GitHub repository. The code snippet below has been functioning smoothly for me. const [posts, loading, error] = useCollection( firebase .firestore() .collection(& ...

An app activation code 401 error suddenly appears, prompting a quick response to refresh the token in the axios interceptor feature

AxiosConfig.js import axios from "axios"; import { store } from "./redux/store"; import { login, logout } from "./redux/slices/user"; const baseURL = process.env.NEXT_PUBLIC_API_URL; axios.defaults.baseURL = baseURL; expor ...

React - the state fluctuates

The Goal I'm Striving For: Transmitting data from child to parent. My Approach: Utilizing this.state as outlined here Having trouble summarizing the issue: Upon calling console.log(this.state) in the function where I update the state, the correct va ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Is there a way to append items to the main level of an array?

I am attempting to populate an array with objects in order to achieve the following structure: myobject1: Object: ItemInside: Object myobject2: Object ItemInside: Object myobject3: Object ItemInside: Object myobject4: Object ItemInside: Ob ...

Swap out the old nested array for a fresh array

Currently, I am dealing with an array nested inside another array. The structure looks like this: Structure: First Array [ { Second Array [ { } ] } ] I am attempting to replace all instances of Second Array with a new array that I have cr ...

Is it possible for me to send transactions asynchronously using polkadot-js?

After thoroughly going through the official documentation, I stumbled upon a page discussing how to transfer using polkadot-js const transfer = api.tx.balances.transfer(BOB, 12345); const hash = await transfer.signAndSend(alice); I am curious if it' ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...