0

I'm developing a Next.js application and I need to connect to a backend server that is running on a different port. I'm having trouble figuring out how to establish this connection.

Currently, my Next.js application is running on port 3000, while the backend server is running on port 8000. I want to make API calls from my Next.js pages to the backend server to fetch data and perform CRUD operations.

I have tried using the fetch() function in Next.js to make the API calls, but it seems to default to the same port (3000) as the frontend. I'm unsure how to configure it to connect to the backend server on port 8000.

Here's a simplified example of what I've tried:

fetch('/api/data') // This defaults to port 3000
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Could someone please guide me on how to establish a connection to a backend running on a different port (8000) in Next.js? Any help or suggestions would be greatly appreciated. Thank you!

Jocefyneroot
  • 137
  • 1
  • 11
  • 1
    Maybe something like this is what you're after: [Proxy to backend with default Next.js dev server](https://stackoverflow.com/a/65467719) – Nick Parsons Jul 09 '23 at 03:07

1 Answers1

0

Since you want to fetch from a different origin, you probably want to use absolute urls. In your case that would be localhost:8000. As a matter of fact, where your NextJs application, localhost:3000 and the backend, localhost:8000 are running are two different origins hosted on one computer. So you’ve got to treat these as such. It’s much like hosting two different websites by the same hosting provider. The Domain names conceal the IP of the hosting provider.

This is the best solution, save the location of each origin you want to visit as an environment variable in a .env file. NodeJs and NextJs fully support this. Then fetch calls like yours should be done like this:

let url = new URL('/api/data', baseUrl) //here the baseUrl is that of the origin the request is made to. It’s stored as an environment variable.
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Note: you should look out for cross origin request blocking on the server you are making the request to. I assumed you are in control of it too but if you aren’t please comment so that I can give you a work around.

Drizzle
  • 198
  • 2
  • 11