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

Angular module with customizable configurations

I am interested in developing a customizable Angular 9 module with IVY and AOT enabled. In the latest version of Angular, IVY and AOT are automatically activated: npx @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8 ...

Separating the time and date into distinct variables offers flexibility in how they

Struggling with formatting time in a web component using TypeScript and React. The code below is working: new Date(myDate) .toLocaleTimeString( 'en-US', { weekday: 'short', year: 'numeric', month: 'short', ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

`Need help with adding meta tags to your Next JS metadata?`

I've been attempting to include a meta tag in Next JS 13.4, but so far I haven't had any success. Despite going through the documentation and conducting thorough searches online, I still haven't found a solution. My goal is to add this parti ...

Next.js application encounters XMLHttpRequest ReferenceError when attempting to retrieve firebase storage file URL

I have successfully set up a Next.js (11) app with a functional connection to Firebase version 8.7. I am facing an issue when trying to retrieve the download URL for an image: If I create a function like the one below to fetch the uploaded image - assumin ...

When working with Typescript, you can declare an interface and split its definition across multiple files

I've been developing a software application that utilizes WebSocket with the NodeJS ws package. My networking structure revolves around a module responsible for handling message reception and transmission. Given that I'm working with TypeScript, ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

Can you please provide information on the specific type of decorator used in Vuex, known as the 'vuex-class' decorator

My TypeScript project has the 'no-implicit-any' rule enabled, but I'm facing challenges when it comes to defining types for all of the 'vuex-class' decorators. For instance, when importing the namespaced action @(namespace('f ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

Ways to retrieve files that are not located in the public directory in Next.js

I'm currently working on a project using Next.js and storing files in the root directory under /uploads/qr/myimage.png. How can I access this file within the project? I attempted to create a route /api/getImg/route.js dedicated to serving image files, ...

When attempting to launch the Next.js DEV server using a specific IP address and port, an error message of "get

Running a development server on my local area network (LAN) has always worked fine for me in the past, but recently I've been encountering an error when trying to run servers like Vite or NextJS on 192.168.1.7:3000. Here is a screenshot of the error ...

How should one begin a new NativeScript-Vue project while implementing Typescript support in the most effective manner?

Is it possible to incorporate Typescript into Vue instance methods? I found guidance on the blog page of nativescript-vue.org. Whenever I initiate a new nativescript-vue project using vue init nativescript-vue/vue-cli-template <project-name>, some w ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

Implementing onClick functionality to change background color with styled components

Is there a way to apply background color when a user clicks on any page in pagination using React styled components? I was able to achieve this with simple CSS by adding the class ".selected" which had a background-color of red, but now I need to use React ...

Optimal method for displaying the children component twice in Next.js

In order to create an infinite slider, I had to duplicate the data within my component. The data consists of an array containing a maximum of 20 items, each with an image. The slider is functioning perfectly. Although it may seem unconventional, it was n ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

What is the method for comparing fields within an input type in type graphql with the assistance of class validator decorators?

I am working with the following example input type: @InputType() class ExampleInputType { @Field(() => Number) @IsInt() fromAge: number @Field(() => Number) @IsInt() toAge: number } Can I validate and compare the toAge and fromAge fields in th ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

What steps can be taken to resolve the link prefetch warning in a Next.js application?

I am currently working on a Next.js application using version 13.4, and I've encountered a warning in the console: After preloading the resource at <URL>, it was not used within a few seconds of the window's load event. Please ensure that i ...