0

I'm trying to fetch data using fetch("/api/status"), but it only finds URL when I use the absolute path: fetch("http://localhost:3000/api/status") . Without using your path saved in a variable.

  • Are you using that `fetch` within the server scope (server component or SSR)? Because, if yes, you need the absolute path, because the server doesn't knoq whats the host. – Robin Thomas Aug 28 '23 at 23:38
  • @RobinThomas I'm using the server component, so there's currently no way to use a relative path? – GabrielCard Aug 29 '23 at 00:19

1 Answers1

0

Since you are using the fetch within a Next.js server component, fetch will not work without absolute url.

However, constructing a request with new Request(url) or running fetch(url) when url is a relative URL does not work

https://nextjs.org/docs/messages/middleware-relative-urls

So you have a few options to get it working:

  1. Convert your server component to a client component. Relative urls will work fine in client component.

  2. Save the host in a variable (or better an environment variable)

  3. Use a third-party library like axios instead of fetch. With this, you can create a global instance just for your host.

import axios, { AxiosRequestConfig } from 'axios';

const axiosInstance = axios.create({
  baseURL: `http://localhost:3000`,
  headers: {
    'Accept': 'application/json',
  },
});

Then use axiosInstance instead of your fetch calls. You can then use relative urls here.

Robin Thomas
  • 1,317
  • 8
  • 15