Why does a Next.js 15 Fetch URL in production on Fly.io change?

When fetching a post on a production next.js 15 hosted on Fly.io the URL that place in the fetch is changing & causing a 404 not found;

The request URL in the network tab of the chrome dev tools is:
https://www.rleaguez.com/organizationz/www.rleaguez.com/api/v2/organization

In console log I log out the url I am using & it’s:

https:www.rleaguez.com/api/v2/organization

The fetch code I am using is:

      const postUrl = process.env.NEXT_PUBLIC_BASE_URL + '/api/v2/organization';
      console.log("🚀 ~ CreateOrg ~ postUrl:", postUrl)
      const orgResponse = await fetch(
        postUrl,
        {
          method: 'POST',
          headers: {
            'content-type': 'application/json',
          },
          body: JSON.stringify(data),
        },
      );

Why does the URL change in production and does not stay the same as what I place in the code?

If I place this line:
https://www.rleaguez.com/api/v2/organization’,
instead of the variable
postUrl,

then the fetch post will function correctly;

I mentioned this in your other thread…

This is not valid URL

@khuezy I appreciate the feedback; The URL https://www.rleaguez.com/api/v2/organization is a valid url for the API to post to; however not a valid frontend page;
I am wondering why the URL changes when it’s a variable in production but when the url to post to in the fetch is hardcoded it stays & is successful.

The problem appears to be that NEXT_PUBLIC_BASE_URL in production contains the full path.

Try:

const postUrl = new URL('/api/v2/organization', process.env.NEXT_PUBLIC_BASE_URL).toString()

You don’t have the two forward slashes, the fetch will fail as it’s an invalid protocol via the URL constructor

2 Likes

I appreciate all of the assistance! That is correct I did not have the 2 forward slashes; after I added that then the post url variable was correct & it too posted successfully. After reading this latest comment I realized it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.