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
Avatar
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,
  });
Image

23 Replies

Avatar
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
Avatar
CursinuOP
env isnt the issue as i can hardcode it and it still works the same
and the backend api does respond correctly
Avatar
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
Avatar
CursinuOP
which /corporation_members/undefined is NOT part of env or the api
the env is this
Avatar
Sun bear
But it is not available client side. So you get "undefined"
Avatar
CursinuOP
so i would have to make my api public ?
Avatar
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,
  });
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
Avatar
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
Avatar
Sun bear
Most likely you have to set it up in fastapi to allow requests from different origins
Avatar
CursinuOP
but i think i found the issue but not sure propper route
i think i need to useEffect with useSWR
Avatar
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
Avatar
CursinuOP
while im getting cors errors
i dont care about them as id rather be able to get to the api via the backend dns and not localhost