Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side:

export const getData = async (): Promise<any> => {
  const response = await fetch(`/data`, {
    method: 'GET',
    headers: CONTENT_TYPE_JSON,
  })
  if (!response.ok) {
    //handle error
  }
  //continue processing data
}

If this function is called from the server:

export const getServerSideProps: GetServerSideProps = async () => {
  getData().then(() => {
    //do something
  })
}

An error occurs because it's not an absolute URL. One solution is to create a similar function with a different URI:

export const getData = async (): Promise<any> => {
  const response = await fetch(`http://myapp/data`, {
    method: 'GET',
    headers: CONTENT_TYPE_JSON,
  })
  if (!response.ok) {
    //handle error
  }
  //continue processing data
}

Another option is to pass a prefix URL argument to getData.

Is there a more generic way to dynamically add the absolute URL part when calling from server-side rendering?

Answer №1

If you have set up a proxy in your next.config.js, please note that it only applies to client-side requests. If you are making requests from the server (such as within getServerSideProps), you should directly call the external API.

In cases where the APP_API environment variable is not exposed to the browser (as it does not have the NEXT_PUBLIC_ prefix), you can use this as a condition to decide whether to use the direct API endpoint on the server or the proxy endpoint on the client.

export const getFooBar = async (): Promise<any> => {
    const url = process.env.APP_API ? `http://${process.env.APP_API}/bar` : '/foo/bar'
    const res = await fetch(url, {
        method: 'GET',
        headers: CONTENT_TYPE_JSON,
    })
    // Remaining code
}

It's also possible to use other conditions to determine if you are on the client or server side, for example by checking typeof window === 'undefined'.

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

Diminish, then lead to a fresh page

I have encountered an issue with my code. The wrapper performs a fade out effect before redirecting the user to a URL. However, it only fades out once and I suspect this is due to the browser caching or loading the page quickly. Is there a way to ensure t ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

Why isn't the externally loaded JS file executing properly?

My javascript code functions properly when it's embedded within the HTML file. However, I encounter issues when I try to import it externally. The Google Developer Tools indicate that the file has been loaded successfully, but there seems to be no vis ...

Effective ways to narrow down data in vuetify v-autocomplete component using Fuse.js

In my application, I am using the Vuetify autocomplete component. This component allows for the use of a custom filter to filter input data. Below is an example of a custom filter for the autocomplete: customFilter (item, queryText, itemText) { const ...

transfer properties to a dynamic sub element

I am currently working on a multi-step form project. I have successfully implemented the form so that each step displays the corresponding form dynamically. However, I am facing challenges in passing props to these components in order to preserve the state ...

Using Java beans to present form data utilizing session

How can I utilize Java Beans and session beans to store user input data and display a preview of the entered details on the next page? I have already created a servlet using JSP, but now I want to incorporate Java Beans to showcase the form data. How shoul ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

Issue with default behavior of infinite scroll in Angular 4

I'm currently working on incorporating infinite scroll into my Angular 4 application. I've carefully followed all the guidelines provided on https://www.npmjs.com/package/ngx-infinite-scroll According to the documentation: By default, the dir ...

Convert file_get_contents from PHP to JavaScript

I previously developed a webpage using php along with a webAPI, but now I am looking to transition it to javascript. The issue at hand: The current site takes about 5-7 seconds to load due to loading a large amount of data, which is not ideal. I want to ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

Ensuring the consistency of actions through thorough testing

Currently utilizing xstate for the implementation of a login flow. Within my machine, the initialState triggers a Promise, which redirects to a state with an entry action if rejected. I am seeking to properly test the timing of when this action is called. ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Is there a way to conclude an Inquirer prompt depending on the response received?

My current project involves creating an application that presents a series of questions to gather information and generate an employee profile. This application is designed to be recursive, meaning that users will have the option to exit and terminate the ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

Optimizing images for CSS background in Next.js

How can I efficiently optimize background images in styled-components using Next.js new feature, without relying on the Image component? ...

What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not. ...