Having trouble retrieving JSON file in Next.js from Nest.js app on the local server

Having just started with Next.js and Nest.js, I'm struggling to identify the issue at hand.

In my backend nest.js app, I have a JSON API running on

http://localhost:3081/v1/transactions
. When I attempt a GET request through postman, everything functions correctly.

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

Below is my index.tsx file within the Next.js frontend application:

import type { GetStaticProps, NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { GetTransactionsResults, Transaction } from "../transactions.types";

const Home: NextPage<{ transactions: Transaction[] }> = ( { transactions }) => {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Image src={"/logo.png"} width={120} height={32} />

        {transactions.map((transaction) => {
          return <li key={ transaction.id }>{ transaction.asset }</li>
        })}

      </main>
    </div>
  );
};

export const getStaticProps: GetStaticProps = async (context) => {
  const res = await fetch("http://localhost:3081/v1/transactions");
  const { results }: GetTransactionsResults = await res.json();
  return {
    props: {
      transactions: results,
     },
  };
};

export default Home;

And here is the interface in transaction.type.ts:

export interface GetTransactionsResults {
  info: Info;
  results: Transaction[];
}

export interface Info {
  count: number;
  page: number;
  next: string;
  prev: null;
}

export enum TransactionNature {
  Deposit = "Deposit",
  Withdraw = "Withdraw",
  Rewards = "Rewards",
  Interest = "Interest",
}

export interface Transaction {
  id: string
  nature: {
    code: TransactionNature
  }
  amount: number
  asset: string
  user: {
    id: string
  }
}

Upon attempting to load the frontend, I encounter the following error message:

Server Error
Error: Error serializing `.transactions` returned from `getStaticProps` in "/".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

It appears to be receiving an empty response from the backend app...

I've also tested fetching data from another web API like this one: and it works fine.

There seems to be something missing here, apologies if this is a basic question but I am very new to this.

Answer №1

After exploring the documentation thoroughly, I managed to come up with a solution.

I carefully studied the documentation and refactored the function as shown below:

import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { GetTransactionsResults, Transaction } from "../transactions.types";

const Home: NextPage<{transactions: Transaction}> = ({ transactions }) => {
  return (
    <div className={styles.container}>

          Object.values(transactions).map(transaction => {
            return <li key={transaction.id}>{transaction.asset}</li>
          })
        }

    </div>
  );
};

//Fetch API data
export async function getStaticProps() {
  // Fetch data from an external API endpoint.
  const res = await fetch('http://localhost:3081/v1/transactions');
  const results: GetTransactionsResults = await res.json()

  // Returning { props: { transactions } } will pass `transactions` as a prop during build time
  return {
    props: {
      transactions: results,
    },
  }
}

export default Home;


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

Python - Error: Invalid JSON data with additional information

Having an issue aggregating data from multiple json files: path_to_json = 'generated_playlists/p1/' json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] The format of the json files is as foll ...

How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this. Let's assume there exists a class class Foo { bar: string; baz: number; bob: a ...

Modifying app aesthetics on-the-fly in Angular

I am currently working on implementing various color schemes to customize our app, and I want Angular to dynamically apply one based on user preferences. In our scenario, the UI will be accessed by multiple clients, each with their own preferred color sch ...

Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html: <button ion-button item-right> <ion-icon name="md-add-circle" (click)="save();"></ion-icon> </button> The content of file.ts is: editmode = false; I am trying to achieve the foll ...

Generate a dynamic request by progressively incrementing variable values within JMeter

Here is the response from a request: **{ "Packages":[ { "CreatedBy":"Administrator", "CreatedDate":"\/Date(1535635263383)\/", "DeviceFamily":6, "LastVersion":{ "BuildVersion":"1.0 ...

Tips on how to extract particular JSON information from an HTTP request by utilizing jQuery

I am attempting to extract the exchange rate from the JSON http response below by using jquery. Assume that jquery has already been included within the <head></head> tags. { "Realtime Currency Exchange Rate": { "1. From_Currency Co ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Discovering all instances of a particular name in JSON using incremented values: a guide

I am looking to automatically detect every occurrence of a specific name in my JSON data. { "servergenre": "Classic Rock", "servergenre2": "pop", "servergenre3": "rock", "servergenre4": "jazz", "servergenre5": "80s", "serverurl": "http://www.n ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

Retrieving all key value pairs from an intricate JSON payload with PHP

After receiving a JSON file from the server, I am facing the challenge of extracting all key:value pairs using PHP. Despite my efforts, my success so far has been limited. Has anyone encountered this issue before? I have been unable to find a solution yet ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

Adding a new attribute-value pair to an existing json11 object in C++ - some useful tips!

For instance, I'm creating a JSON message using the code snippet below: json11::Json my_json = json11::Json::object{ { "key_val1", val1}, { "key_val2", val2}, { "key_val3", val3}, { "key_val4", val4 } }; std::string message = my_json ...

When utilizing a Service through UserManager, the User variable may become null

Utilizing Angular 7 along with the OIDC-Client library, I have constructed an AuthService that provides access to several UserManager methods. Interestingly, when I trigger the signInRedirectCallback function from the AuthService, the user object appears ...

Substitute a JSONP API call using $.ajax() with a direct server-to-server API call

My javascript application utilizes an ajax function that has the following structure: $.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) { if (data.ok) { //perform actions }}}); Everything was working perfectly until I ...

Troubleshooting ORA-02290 error when storing JSON in Weblogic's CLOB column

We encountered an issue when attempting to save a JSON string to a database column defined as a CLOB. The error message received is as follows: Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-02290: check constraint (MYSCHEMA.MY_JSON_CHK ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

What is the best way to initiate server component revalidation following an API request in NextJs 14?

I currently have a server component ("/") in place which directly queries my database using Drizzle. The UI is designed to look different if the user has at least one file. However, I am facing an issue where even after calling a specific route from a di ...