Machines API not working from within a NextJS App

Hi everyone,

I’m trying to work with the Machines REST API and make some calls to it from within my NextJS App, but somehow I always get the error “failed to fetch” without any further error description. Do you know what could cause this behavior? I tested my request in Postman and it works fine there, but once I try the exact same request in my app, it throws me an error. Here is my code for making the request:

const flyResponse = await fetch("https://api.machines.dev/v1/apps/<app>/machines/<machine>",
                {
                  method: "GET",
                  headers: {
                    "Content-Type": "application/json",
                    Authorization:
                      "Bearer " + process.env.NEXT_PUBLIC_FLY_TOKEN,
                  },
                },
              );
              const responseJson = await flyResponse.json();
...

The environment variable is set and works fine, I used the same in Postman. Thanks in advance for your help and have a nice day!

Best,
Magnus

console log this to make sure the app name and machine id is correctly generated.

Never use NEXT_PUBLIC_ for sensitive data… this is a security vulnerability waiting to happen.

I already logged both values (in fact the app name is hardcoded but I double checked the machine id) and they are correctly set meaning they are the same as in the Postman requests. The security issue with the token is on my list, thanks!

Try using http://_api.internal:4280 instead of the public one since you’re calling from within the fly machine.

I was able to use fetch and the public endpoint in my next app to interact w/ the fly machine APis.

I suspect a CORS issue. I see you are using NEXT_PUBLIC_… are you trying to access the API within your browser?

You might be better off creating a Next.js API route which inserts the authorization token and makes the request on behalf of your application, and returns the response it gets from that request as its response. And then change the code that runs within the browser to make a request to your API.

Okay so moving the requests to the server somehow did the trick and now everything works, thanks for your help @khuezy @rubys

You need to revoke your Fly token, as it was exposed to the front end. Bots will hit public apps and scrape for secrets.

@khuezy thanks but the app isn’t live yet so the token hasn’t been published anywhere