"Strange Type Conversion Behavior in next.js 13: Why is res.json() Converting Numbers to Strings

I have encountered a strange issue where no matter what I do, the fetched data is being partially converted to strings. For example, the 'bialko' and 'kcal' fields are supposed to be of type Float in Prisma, yet they are getting casted as Strings when fetched. However, after changing the data type from decimal to double precision, the API endpoint returns the objects correctly. But the fetch operation still behaves unexpectedly. It's worth noting that I am fetching data on the server side!

What I have tried so far: - Recreating the entire database, altering columns, changing data types from numeric to double precision - Running npx prisma generate, prisma migrate, deleting migrations

Backend code:

export async function GET(request: Request) {
    const zestawyWo = await prisma.rankings.findMany({
        where: {},
        select: {
            id: true,
            price: true,
            bialko: true,
            kcal: true,
        },
    })

    if (zestawyWo.length == 0) {
        return NextResponse.json(
            {error: "zestawyWo not found"},
            {
                status: 404,
            }
        )
    }

    console.log(typeof zestawyWo[0].bialko)
    console.log(typeof zestawyWo[0].price)
    console.log(zestawyWo)

    return NextResponse.json(zestawyWo, {
        status: 200,
    })
}

Component code:

async function fetchAllZestawy(orderby?: string): Promise<Zestaw[]> {
    const res = await fetch(`http://localhost:3000/api/zestawywo`)
    const data: Zestaw[] = await res.json()
    console.log(typeof data[0].bialko)    // string
    console.log(data)   //  result pasted below
    return data
}

EDIT: When I tried fetching data in the CLIENT COMPONENT, everything worked correctly (returned kcal and bialko as numbers). It seems like there is some sort of anomaly happening with next.js FETCH.

useEffect(() => {
        ;(async () => {
            const res = await fetch("http://localhost:3000/api/zestawywo")
            const result = await res.json()
            console.log("CLIENT", result)
        })()

CONSOLE.log OF DATA THAT SHOULD BE FETCHED

  {
    id: 8,
    price: 31.9,
    bialko: 58.2,
    kcal: 1581,
  }

CONSOLE.log OF FETCHED DATA

  {
    id: 8,
    price: 31.9,
    bialko: "58.2",
    kcal: "1581",
  }

Answer №1

Avoid creating and exporting a separate function for each method. Consider the following approach:

import { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // your database operations
  res.status(200).json(data);
}

If you need different callbacks for each HTTP method, you can utilize a switch statement like this:

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
      case "GET": handleGet(),
      case "POST": handlePost(),
      // ...and other methods
  }
}

For more details, refer to: https://nextjs.org/docs/api-routes/introduction

Answer №2

Believe it or not, the issue was fixed by simply changing localhost to 127.0.0.1 in the fetch URL.

const res = await fetch('http://127.0.0.1:3000/api/zestawywo')

It seems like Next.js has some issues with its fetch functionality, as I accidentally stumbled upon a solution while trying to fix another bug. The same method worked for both:

TypeError: fetch failed in server component

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

Creating a digital collection using Vue, Typescript, and Webpack

A short while back, I made the decision to transform my Vue project into a library in order to make it easier to reuse the components across different projects. Following some guidelines, I successfully converted the project into a library. However, when ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Creating an HTTP method handler function in Next.js API routes with an unspecified number of generic parameters

Looking to create a wrapper function in NextJS for API routes that can handle multiple HTTP methods with different handlers. For example, check out the TS playground interface GetResponse { hello: string, } // empty object type PostResponse = Record&l ...

Ways to populate missing cells with a default hyphen symbol

Looking for a way to default empty cells in my primeng datatable to '-'. Consider the following data: [ { 'column': null }, { 'column': { 'name': 'A' } }, { 'column': { 'name': ...

What could be causing the error message "why can't shows read property

Within my Ionic-Angular application, I have successfully loaded the content from the database and printed it on the console. However, I am facing an issue where I cannot bind this content to the view. The error message that appears is displayed in https:// ...

Guide on transmitting data between NextJS and MongoDB

I'm facing an issue where the data from a form is being sent to MongoDB as undefined using nextJS and MongoDB. NewPlayerPage component: const newPlayerPage = (props) => { console.log('props: ' + props); const handleAddPlayer = a ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...

Navigating from an error page to the homepage with Next.JS 13: A quick and easy guide

I'm currently working on implementing a feature that allows users to easily go back to the main page from an error page within the app folder. Specifically, in my weather app project, if a user enters an incorrect city, they should have the option to ...

Do we actually need to define routes for dynamic routing in Next.js?

For my movie website project, I have a huge amount of data with hundreds of thousands of unique movie ids. Is there a better solution than listing all the ids for routing purposes? Due to the limitations of the API, I am required to make numerous calls t ...

Effortlessly proxy AJAX requests in development as well as production settings

Currently, my project is utilizing Next.js along with the Axios libraries. The structure of my axios requests is as follows: axios.get('/api/users/1') Initially, this setup worked perfectly fine when both the API and rendering server were loca ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Guide on generating a video thumbnail using JavaScript Application

Searching for a way to easily create a thumbnail from a video for uploading alongside the video itself to a server? I've been looking for JavaScript libraries to simplify the process without much luck. The scenario involves the user selecting a video ...

We are sorry, but there seems to be a server error displaying the message:

After following the instructions in this tutorial: https://youtu.be/mx1dbMzd3tU I encountered an issue when attempting to connect sanity and next: Server Error Error: Configuration must contain projectId‘ ...

Executing GraphQL mutation server-side utilizing an Apollo server with a Node.js script

I am currently running a scraping script using Puppeteer, and my goal is to save each scraped row into the database. However, I have encountered an error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This ...

The error message "Unable to find function getFieldProps in formik" is displayed

A Field component was recently added to useFormik in my Nextjs app, causing this error message to appear: Server Error TypeError: formik.getFieldProps is not a function This error occurred while generating the page. Any console logs will be displayed in th ...

The typescript compiler encounters an error when processing code that includes a generator function

Recently, I started learning about TypeScript and came across the concept of generators. In order to experiment with them, I decided to test out the following code snippet: function* infiniteSequence() { var i = 0; while(true) { yield i++ ...

How do I insert items into an ES6 Map using a specific object key/value type in Typescript?

I'm looking to utilize Maps instead of object maps to define keys and values. However, it appears that Typescript doesn't fully support index types for ES6 Maps. Are there any alternatives or workarounds available? Furthermore, I want to enforce ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Instead of being viewed in the browser, the CSV file is being downloaded

I'm currently using Jhipster and have a function generated by Jhipster to open files in the browser. However, I'm facing an issue with this function when it comes to opening CSV files - instead of opening in the browser, they are being downloaded ...