How to perform a fetch on a local path in Next.js?

Is there a way to use the fetch method with a relative path like this:

export async function getServerSideProps() {
    // Fetch data from local API
    const res = await fetch(`/api/get_all_prices`)
    const data = await res.json()
    // Pass data to the page via props
    return { props: { data } }
}

function HomePage({props}) {
    return (
        // use props here
    )
}

I need this code to be able to work in both development and production environments without having to change the URLs for different computers or servers, as it can lead to unnecessary issues.

Any tips on how I can retrieve data from my local API route?

I've noticed that the fetch method doesn't seem to work with local routes. Is there any workaround for this issue?


[EDIT]

After some research, I found a solution using a library called superjson.

I was originally trying to use the API directly because of serialization issues with Prisma when using getServerSideProps (it returns Date objects that can't be serialized in JSON).

The best approach was to write a common file for the method, utilize superjson for proper serialization, and then call that method within getServerSideProps.

This results in clean code that is compatible with Next.js.

Answer №1

If you want to make a request, you can do it in the following way:

fetch('http://localhost:3000/api/get_all_prices')
or use a variable for the base URL like this:
fetch(baseUrl + 'api/get_all_prices')
. However, be aware that using a variable may result in an error message stating:
Only absolute paths are supported
. It is advisable to only test local APIs because...

Avoid using fetch() to call an API route within getServerSideProps.

This information is outlined in the documentation

It is suggested to incorporate your logic directly into getServerSideProps. This guideline also pertains to getStaticProps.

Answer №2

Only absolute paths are supported
- this is the kind of error you might encounter in a production environment.

In order to resolve this issue, it is necessary to configure your environment variables correctly.

Ensure that your path resembles something like the following:

const response = await fetch(process.env.APIpath + `/api/get_all_prices`)

Additionally, remember to configure variables on Vercel's platform.

Answer №3

By utilizing the default next.js API, there is no need to worry about ports, domains, or other technical details as next.js handles them automatically. If everything functions correctly in development mode, there should be no issues when switching to production, even if there are changes in domain or port settings.

Furthermore, next.js has a built-in routing mechanism that is useful for masking actual URLs or implementing pure node functionality. For instance, you can have a route named api/posts, but behind the scenes it sends requests to another API located at https://backend. This setup helps maintain clarity and organization in your network console by displaying requests sent to the correct endpoints.

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

How can we ensure that only one of two props is specified during compilation?

I've designed a customized Button component. interface Button { href?: string; action(): void; } I'm looking to ensure that when a consumer uses this Button, they can only pass either href or action as a prop, not both. I want TypeScri ...

What could be the reason for the tsc command not displaying compilation errors when compiling a particular file?

My file, titled app.ts, contains the following code snippet: interface Foo { bar:String; } const fn = (foo? :Foo) => foo.bar; When I run tsc from the root folder with strict:true in my tsconfig.json file, I receive an error message like this ...

Using D3 to create SVG elements in Next.js, the mouseenter event only triggers once

I'm currently developing a React Component that utilizes D3, however, I am facing an issue where the SVG circles are only triggered once. import React, { useEffect, useRef, useState } from 'react'; import * as d3 from 'd3'; import ...

Angular 6 issue: Data not found in MatTableDataSource

Working on implementing the MatTableDataSource to utilize the full functionality of the Material Data-Table, but encountering issues. Data is fetched from an API, stored in an object, and then used to create a new MatTableDataSource. However, no data is b ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Using Angular to include a forward slash "/" in the text input for a date field

Hello everyone, I am a newcomer to AngularJS and I am looking to insert slashes in an input type text element. I prefer not to rely on external packages like angular-ui or input type Date. My goal is to have the format mm/dd/yyyy automatically applied as ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

What is the reason behind the mandatory credentials option for the CredentialsProvider?

When using NextAuth.js with a custom sign in page, some code examples for the credentials provider do not include the credentials option in the CredentialsProvider. According to the documentation (here), the credentials option is meant to automatically "ge ...

Bug Found in ClerkJS Authentication() and RetrieveUser() Functions within Server-Side Components & Server-Side Actions in Newest Next.js Release

I have followed the steps provided in the clerkjs documentation and here is my middleware.ts file : View middleware.ts file Additionally, this is the code snippet for the page.tsx, which serves as a server component: import { getUserByClerkId } from " ...

Vercel prevents Google from including website in search results

After deploying my Next.js app on Vercel, I encountered an issue where Google's crawl requests were returning a 401 unauthorized error. This problem is also evident in the deployment logs console as indicated below: Even though I added the URL to the ...

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Highcharts - Customize Pie Chart Colors for Every Slice

I'm working on an angular app that includes highcharts. Specifically, I am dealing with a pie chart where each slice needs to be colored based on a predefined list of colors. The challenge is that the pie chart is limited to 10 slices, and I need to a ...

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Buttons for camera actions are superimposed on top of the preview of the capacitor camera

I am currently using the Capacitor CameraPreview Library to access the camera functions of the device. However, I have encountered a strange issue where the camera buttons overlap with the preview when exporting to an android device. This issue seems to on ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...