Error: only absolute urls are supported occurs in Next.js when you try to make a fetch or network request to a relative URL instead of an absolute URL.
How to fix the error?
To fix the only absolute urls are supported error in Next.js, hardcode the server address into your fetch request.
For example, if you are trying to fetch data from an API using the fetch function or any other HTTP request library.
Incorrect (Relative URL):
Correct (Absolute URL):
If you are working on real-time projects, then you should define your configuration like this:
const dev = process.env.NODE_ENV !== 'production'; export const server = dev ? 'http://localhost:8000' : 'https://your_main_server.com';
In a Next.js environment (especially during server-side rendering or static site generation), you must specify the full URL, including the protocol (http or https) and the domain name.
Using environment variables, you can easily switch between different base URLs depending on the environment without changing the code.
Remember to add the NEXT_PUBLIC_ prefix to environment variables if you want them to be accessible on the client side in Next.js.
Summary Table For Error, Cause, and Solution
|Issue||“only absolute urls are supported” error in Next.js|
|Cause||Using relative URLs when making network requests in Next.js|
|Incorrect Way (Relative URL)||
|Correct Way (Absolute URL)||
|Solution||1. Always use absolute URLs.
2. Use environment variables for the base URL.
|Environment Variable Example||const BASE_URL = process.env.NEXT_PUBLIC_API_URL|
|Note on Environment Variables||Add