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

Sending asynchronous requests to handle data within various functions based on different links

I'm currently facing a major roadblock when it comes to resolving my issues with callbacks. I've gone through resources like How to return value from an asynchronous callback function? and How to return the response from an Ajax call?, among seve ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Remove the active class from a list item using History.js

My goal is to add the active class to a link when clicked in my AJAX app, triggering statechange on History.js. I'm struggling with saving the current active link(s) with the state so that the active class is appropriately added or removed when naviga ...

Convince me otherwise: Utilizing a Sinatra API paired with a comprehensive JS/HTML frontend

As I embark on the journey of designing a social website that needs to support a large number of users, I have come up with an interesting approach: Implementing Sinatra on the backend with a comprehensive REST API to handle all operations on the website ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

Tips for maintaining the 'client use' code snippet at the beginning of your Vs Code script

In my quest to utilize the NextJs app directory, I've come across a dilemma. To implement client-side components, it mandates the usage of 'use client' at the beginning of the file. However, Vs Code has a tendency to relocate this statement ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Is it considered fundamentally inappropriate to call $scope.$digest within $scope.$on?

I recently inherited some AngularJS code, and my knowledge of both the codebase and Angular itself is limited. Within the code I inherited, there are instances where $scope.$digest is being called inside a $scope.$on method within a controller. Here's ...

Having trouble with nextjs routes not displaying the Modal?

Struggling to get the intercepting routes feature of Next.js' new app router to work with a Modal. The issue is, the Modal never renders and only the URL changes. My project structure is as follows: /app @modal (.)user [id] page.js user [ ...

"Encountering an unfamiliar authentication strategy while using NodeJS passport

I am currently developing a project using node.js with passport authentication. However, I am encountering the following error message: Error: "Unknown authentication strategy " Below is my code: LocalStrategy = require('passport-local').Strat ...

Is there a method to delay the loading of a webpage until an image has fully loaded (preloading)?

How can I ensure that an image used in a preloader is loaded before the other contents on my website? <div class="overlay" id="mainoverlay"> <div class="preloader" id="preloader"> <img src="images/logo128.png" id="logo-p ...

Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server ...

What is the best way to manage a new Error in Node.js while utilizing ES6 Symbols?

In my node.js application, I am implementing an endpoint using ES6 Symbols. Here is an example: // ES6 Symbol Method const taskCreationMethod = { [Symbol.taskMethod]() { return { storeCheckFunc: async function(storeId, employeeId) ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Error: The term "Image" is unrecognizable

I'm in the process of creating a website where I want to display images via links. If the image is missing or only 1 pixel wide, I need the site to show an alternative image. My technology stack includes Jade/Pug and JS. Before rendering the links on ...

Ignoring the incremented value in a jQuery function

I have been struggling to resolve this issue for quite some time now, and unfortunately, my lack of proficiency in javascript is hindering me. Here's a jfiddle with an interesting jquery code snippet that I came across: [html] <button id="addPro ...

Preserving alterations to media files using an image cropper

I've created a special controller for an image cropping tool that pops up over a media item in the content section. Right now I can manipulate the crops in the overlay, but when I click "Save Crops", the changes don't stick. However, if I use the ...

Is there a way to instantiate a new object within the same for loop without replacing the ones created in previous iterations?

My current issue with this exercise is that as I convert the first nested array into an object, the iteration continues to the next nested array and ends up overwriting the object I just created. I'm wondering how I can instruct my code to stop itera ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...