Having issues with Next.js server-side rendering when integrating API functionality

"Not building properly" means that the project is not fully completing the build process. I've developed a simple blog project with dynamic SSR that pulls data from the Notion-API to generate static blog pages. Everything functions correctly when running in next dev, but when attempting to build the project, it enters into an endless loop without displaying any errors.

One theory I have is as follows:
If my understanding of the sequence is correct, Next.js attempts to build the static sites during next build. The dynamic site generation relies on an API coded within the same project, which sends requests to Notion to hide secrets. Since no local API is active during the build process, I suspect this may be causing the error I am encountering?

To demonstrate - here is the code for the pages to be generated:

import Head from 'next/head';

export default function Post( { postData, postBlocks } ) {
  console.log( { postData, postBlocks } );
  return (
    <>

      <Head>
        <title>Placeholder</title>
        <meta name="description" content="" />
      </Head>

      <h1>Placeholder</h1>

    </>
  )
}

// Get further info on the specific "Post" from Notion via my API
export async function getStaticProps( { params } ) {
  const postDataRequest = fetch( `${ process.env.API_ROOT }/posts/${ params.id }` );
  const postBlocksRequest = fetch( `${ process.env.API_ROOT }/blocks/${ params.id }` );

  const [ postData, postBlocks ] = await Promise.all(
    ( await Promise.all( [ postDataRequest, postBlocksRequest ] ) )
      .map( response => response.json() )
  );

  return {
    props: { postData, postBlocks: postBlocks.results },
    revalidate: 86400,
  };

}

// Fetch all "Posts" from Notion via my API, retrieve their ID and generate a static route for each 
export async function getStaticPaths() {
  const req = await fetch( `${ process.env.API_ROOT }/posts?limit=999` );
  const data = await req.json();

  const paths = data.results.map( page => {
    return { params: { id: page.id } };
  } )

  return {
    paths,
    fallback: false,
  };
}

I've attempted starting the API locally and building the project in another terminal, but this also did not work. Have I overlooked something somewhere?

I have shared my project on GitHub for further examination.

Answer №1

After a careful consideration, I realized that creating an API was not necessary for this task. With the Notion keys already available project-wide in process.env, I could streamline the query-logic by moving it to helper functions. This approach proved to be successful in resolving all the challenges I encountered.

Lesson learned: Avoid the temptation to create APIs for every situation as it can unnecessarily complicate your workflow.

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

What is the process for modifying a task on my to-do list with a long press?

I'm currently working on implementing a task update feature in my project. However, I've encountered an issue where the prompt only works in the browser environment. Is there a way to make this work in React Native or are there any alternative so ...

Utilize store functions (such as dispatch and getState) in external modules like webSockets, rather than within components

I have implemented React and Redux, along with webSocket to handle server side events. Currently, I can dispatch actions from a component by assigning a function to the dispatcher using the mapDispatchToProps() function. But what if I want to trigger an ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

How to make a form in PHP that can be saved?

I have put together a straightforward, yet lengthy HTML form and I am in need of a way for users to save their progress on the form and return to it at a later time (security is not a major concern). However, I am struggling with how to save the form' ...

Kindly advise me on the best method to persist the updated value within the redux store

Whenever I use the useState hook on my page to modify the displayed screen by scrolling through the HTML tag and adding data, it works perfectly. The scroll value and data are saved in the store when leaving the page so that upon returning, the page scroll ...

Is it possible to access the Express req object inside a Next.js app?

Let's say I have a middleware that includes additional data fields in the express.js req object. My goal is to pass these fields into my React components using my Next.js _app.js. How can I access the req object inside the _app.js file? ...

The functionality of the webservice is not functioning properly

I'm currently working with Express and NodeJS to create a simple hello world webservice. I am attempting to call this webservice in ReactJS using Axios, but I am encountering issues with the response from the webservice. Below is my code for the webse ...

Unable to locate "Gruntfile.js" Node module for task execution

I am currently in the process of developing a module that enables node to execute Grunt tasks via the command line. This Node module is globally installed at : C:\Users\pcharpin\AppData\Roaming\npm\node_modules\task-app ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Using Vue to append elements that are not part of the loop

While looping over a table row, I realized that each of the table rows should be accompanied by another table row containing additional data from the loop. Unfortunately, I am struggling to insert <tr class="data-spacer"></tr> <tr& ...

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...

Implementing role-based authentication in Next.js using Next-auth and Firebase

Currently, I'm in the process of integrating role-based authentication using NextAuth.js into my Next.js application. Despite following the provided documentation meticulously, an error (in profile snippet and callback snippet which I copied from next ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Tips for ensuring nvm is activated whenever the nvmrc file is updated

I have implemented the use of direnv along with an nvmrc file to ensure that nvm install runs every time the directory is entered. This ensures that the correct node version is used when working on the project. However, I have noticed that if another user ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

To link the information within the angularJS controller

I've recently generated a div element dynamically within the controller function of my AngularJS application. However, I'm facing an issue where the data is not binding as expected inside this div element. Here is a snippet of my code: function ...

Dealing with the "TypeError: Cannot read property 'style' of undefined" error in material-ui Transitions: A troubleshooting guide

While attempting to incorporate transitions within my react app, I encountered a recurring error whenever I tried to implement any transition module: "TypeError: Cannot read property 'style' of undefined". (anonymous function) node_modules/ ...

What are the steps to incorporate PointerLockControl in Three.js?

Having trouble correctly integrating the PointerLockControl in Three.js? Despite trying various examples, errors seem to persist. I've been importing libraries through the head part like this: <script src="lib/controls/PointerLockControls.js"> ...