Search code examples
javascriptreactjsnext.jsapp-router

How to use relative path 'fetch' in NextJs App Router?


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.


Solution

  • 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.