An issue arose while pre-rendering the page within Next.js

Recently, I developed an API using next JS in the pages/api directory and utilized it on a page located in the pages folder.

During the localhost testing phase, the API functions smoothly without any issues. However, when deploying to Vercel, I encountered an error in the build process.

https://i.sstatic.net/cOehV.png

Below is the code snippet where I call the API from the pages/api directory:

export const getStaticProps = async () => {
  const baseUrlDribble = 'https://api.dribbble.com/v2';
  const baseUrl = process.env.NODE_ENV === 'production' ?
    'https://jovanka-samudra.vercel.app/api' : 'http://localhost:3000/api';

  const resShots = await fetch(`${baseUrlDribble}/user/shots?access_token=${process.env.TOKEN_DRIBBLE}&page=1&per_page=9`);
  const shots = await resShots.json();

  const resResult = await fetch(`${baseUrl}/projects`);
  const result = await resResult.json();
  const projects = result.data.projects;

  return {
    props: {
      shots,
      projects,
    },
    revalidate: 1,
  }
}

Furthermore, this is the API code responsible for fetching data from the database located in the pages/api/projects directory:

import ProjectService from "@services/ProjectService";
import connectDB from "@utils/connectDB";
import projectValidator from "@validators/project";
import ClientError from '@exceptions/ClientError';

const handler = async (req, res) => {
  const projectService = new ProjectService();

  if (req.method === 'GET') {
    try {
      const projects = await projectService.getProjects();
  
      return res.status(200).json({
        success: true,
        length: projects.length,
        data: {
          projects
        }
      });
    } catch (error) {
      return res.status(500).json({
        success: false,
        message: error.message,
      });
    }
  } else if (req.method === 'POST') {
    ...
  }

  return res.status(404).json({
    success: false,
    message: 'Method not allowed'
  });
}

export default connectDB(handler);

Moreover, the @services/ProjectService folder contains the following code:

import InvariantError from '@exceptions/InvariantError';
import NotFoundError from '@exceptions/NotFoundError';
import Project from '@models/Project';

class ProjectService {
  async getProjects() {
    const projects = await Project.find().sort({ 'createdAt': -1 });

    return projects;
  }

    ...
}

export default ProjectService;

Answer №1

Avoid fetching an internal API route directly from getStaticProps. Instead, consider writing the fetch code in the API route itself within getStaticProps.

Learn more here

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

Obtain facial rotation using Three.js

In my code, I am calculating the intersections of mouse clicks with Three.js as follows: myVector.set( (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5); myVector.unproject(myApp.camera); myRay.se ...

Incorporating the fadeout technique in conjunction with the append() function

Here is some code that I am working with: $('body').on('click' , function(){ $('body').append('<div class="ajax-success"><p>Its Done !!!</p></div>').fadeOut(2000); }); The goal was to a ...

Leveraging variables or constants within a Next.js API

Currently, I am working on incorporating a constant in my API. This particular constant is an array that allows me to push or pop objects as needed. I dynamically populate it through various API calls within the following code snippet: const washes = []; ...

There are no documents found with the specified UUID in MongoDB

I have been attempting to retrieve a specific document from MongoDB that includes the field "ownerId" containing a binary UUID. In the Mongo console, when I run the command db.dataset.find({ownerId: BinData(3,"ZQ6EAOKbQdSnFkRmVUUAAA==")}).pretty() The ou ...

Having trouble interacting with Xpath elements using Selenium and Java?

I have been attempting to access a search bar and submit the query without a SEARCH BUTTON. While I was able to enter the search query using javascriptexecutor, I encountered difficulty when trying to perform an Enter button action as there was no actual E ...

What is the best way to showcase information from an external API in react js?

As I develop my new app, I am integrating API data from . This feature will enable users to search for their favorite cocktail drinks and display the drink name fetched from the API on the page. However, I am encountering an error that says "Uncaught TypeE ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

What is the best way to implement redux-persist with a toolkit and next-redux-wrapper?

Having issues setting up redux-toolkit, redux-persist, and next-redux-wrapper in my configuration. I've been trying to make the redux state persist but it's not triggering the redux actions that are supposed to save the state to local storage. H ...

Encountering an issue with "RangeError: Invalid time value" while trying to pass a variable into the new Date() function

function fetchDate() { const router = useRouter(); const { location, startDate, endDate, numOfGuests } = router.query; const formattedStartDate = format(new Date(startDate), "dd, MMMM yyyy"); const formattedEndDate = format ...

Purging information from JavaScript object

Looking for a way to remove just one piece of data from a JavaScript object in my React app. Here's the structure of the object: state = { data: [] } const contactData = { Datas: { name: "william", email: "<a href="/cdn-cgi/l/email-pr ...

Incorporating external JavaScript files into a React Element

I am currently revamping my Portfolio Site to incorporate modals into one of the pages as part of the transition to a Single Page Application (SPA). The JavaScript code for these modals is stored in a "main.js" file, and the necessary tags are included in ...

How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving th ...

error message: "The mtlLoader Module does not have the export named 'MTLLoader'"

I am struggling with getting the mtlLoader module to work in three.js. I am a beginner and I am trying to import the mtlLoader module from the latest three.js-master repository on the official website. However, I keep encountering this error message when I ...

Using JavaScript, add a complex JSON record to a JSON variable by pushing it

I have been attempting to insert a complex JSON data record into a JSON variable using the following code: var marks=[]; var studentData="student1":[{ "term1":[ {"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]}, {"Work":[{"obtained":"13"," ...

JQuery will only run after the Alert has been triggered in Firefox

I am currently facing an issue with updating the 'like' count in my database using the 'changeRating()' method when a user interacts with local like, Facebook like, or Twitter buttons. Oddly enough, the 'likes' are not being ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...