Next.js Discord

Discord Forum

fetch / or other issue causing GET to go to frontend and not backend

Unanswered
Cursinu posted this in #help-forum
Open in Discord
CursinuOP
I think I'm just doing something very simply wrong but not sure what.
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const {data, isLoading} = useSWR(process.env.BACKEND_API+`/api/db/routes/default?page=${page}&size=${rowsPerPage}`, fetcher, {
    keepPreviousData: true,
  });

23 Replies

Sun bear
Try

NEXT_PUBLIC_BACKEND_API

To access env client side. Of course you also have the variable name im .env file.

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
@Cursinu env isnt the issue as i can hardcode it and it still works the same
Sun bear
Your screenshot shows "undefined" in the get url. Thats because the env is not available clientside.

You are fetching a not existing url
CursinuOP
which /corporation_members/undefined is NOT part of env or the api
the env is this
Sun bear
But it is not available client side. So you get "undefined"
CursinuOP
so i would have to make my api public ?
Sun bear
NEXTPUBLIC should help
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const {data, isLoading} = useSWR(process.env.NEXT_PUBLIC_BACKEND_API+`/api/db/routes/default?page=${page}&size=${rowsPerPage}`, fetcher, {
    keepPreviousData: true,
  });
@Cursinu so i would have to make my api public ?
Sun bear
You are trying to access BACKEND_API client side. Thats not possible. Thats why you get undefined.

Prefix NEXTPUBLIC allows accessing env client side
It is a security feature so that you dont leak secrets by accident.

But a url is not secret so you can use NEXT_PUBLIC

Just not sure if it is really http://fastapi:8000 i would expect http://localhost:8000
CursinuOP
using docker
so im pointing to the container
if i use
http://localhost:8082/api/db/routes/default?page=${page}&size=${rowsPerPage}
then it works but i get a cors issue
Sun bear
Most likely you have to set it up in fastapi to allow requests from different origins
CursinuOP
but i think i found the issue but not sure propper route
i think i need to useEffect with useSWR
Sun bear
In case you are now fetching tge correct route but not get data in return. Check fast api logs. In case you get cors problem see here:

https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware
i dont care about them as id rather be able to get to the api via the backend dns and not localhost