Next.js Discord

Discord Forum

Nextjs with custom backend

Answered
Korat posted this in #help-forum
Open in Discord
KoratOP
@Ray Route handlers are replaced by server actions in next 14 right?
Answered by Ray
no I don't think they will get replaced
View full answer

72 Replies

Answer
KoratOP
i mean its a better way than route handlers
yea
for mutation
KoratOP
and we can use them alongside a custom backend like dotnet in my case ?
yes you can
how are you doing mutation now?
KoratOP
Im using react query
you make the request to backend directly or nextjs?
are you doing any client side fetching?
KoratOP
Im mixing them, some queries im making in the server compoennts, some in the clients, when mutating if the query was in client side, i use invalidateQueries, otherwise, ill use revalidate tag xd
oh ok
KoratOP
but im thinking that if server action work with custom backend , i can drop react query
so you are using route handler?
KoratOP
right
yea I can't find a reason to use react-query yet in app router lol
KoratOP
But, how would you handle global toasters when mutations are successful?
or on errors
<form action={async () => {
  const res = await action(data)
  if (res.success) toast.success()
}}>
</form>
KoratOP
the action is a function that calls fetch right?
KoratOP
do you have a way to handle them globally instead?
and the server action look like this
'use server'

export async function action(data: Formdata) {
  try 
    const res = await fetch("")
    const data = await res.json()
    return {success:true, data}
  } catch (e) {
    return { success: false, errors: ...}
  }
}
KoratOP
yeah
check out sonner
KoratOP
yeah im using shadcn, but for example in react query
we use the global onSuccess right
yes
@Ray ts <form action={async () => { const res = await action(data) if (res.success) toast.success() }}> </form>
KoratOP
is there any way just so we dont always add this
if success
@Korat is there any way just so we dont always add this
what do you mean?
oh I get it now
we have to do it every time
KoratOP
okay brother
or maybe if we created a wrapper around fetch
like we have done
i can show it to ya
we can handle the global onSuccess there
but im not sure if sonner works in functions
inside
aren't you using sonner?
KoratOP
yeah im using it why
@Korat but im not sure if sonner works in functions
in what function?
KoratOP
we have created a wrapper for fetch
inside we take the jwt token from session, next-auth for now until i find a solution without it lol
interface FetchConfig<T = Record<string, string>> {
  options?: RequestInit;
  headers?: T;
}

export async function fetchFromApi<T>(
  endpoint: string,
  config: FetchConfig = {}
): Promise<T | null> {
  // const locale = useLocale();
  const locale = "en";
  const locales: Record<string, string> = { en: "en-GB", fr: "fr-FR" };

  // Getting sessions from next/auth
  const session = await getServerSession(options);
  // Setting default headers
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...config.headers,
  };

  // Setting authorization bearer token (if available)
  if (session?.user?.token) {
    headers["Authorization"] = `Bearer ${session.user.token}`;
  }
  // Setting default options
  const defaultOptions: RequestInit = {
    method: "GET",
    headers: headers,
  };

  // Merging default options with provided options and headers
  const finalOptions = {
    ...defaultOptions,
    ...config.options,
    headers: {
      ...defaultOptions.headers,
      ...config.headers,
    },
  };

  // Making the API call
  const response = await fetch(
    `${API_URL}/${locales[locale]}/${endpoint}`,
    finalOptions
  );
  const responseData: Response<T> = await response.json();
  // Checking API response success status
  if (!responseData.isSuccess) {
    throw new Error(
      responseData.errors?.map((e) => e.message).join(", ") || "Unknown error."
    );
  }

  return responseData.data;
}
See what i mean
this should work in server action
KoratOP
but does sonner work inside of this haha
no lol
KoratOP
yeah, so no global configuration for sonner then hahah we have to handle it on every mutation right
KoratOP
aight brother
yea or you can create a function for it
const res = await action(data)
handleToast(res)
KoratOP
Yeah that too, okay ill start testing things out, gotta change the mentality a bit because we have used react query
one more thing, what do you use for internationalization ?
next-intl
KoratOP
this one ?
yea
this look good too but no time to test it yet
KoratOP
I wanted to ask you about this case we have, because we are forced to use axios in one of the projects, and the backend requires to send the lang in the url like this /api/en-GB/users
we tried to get it somehow inside the axios interceptor
and set the base url
I just answered to someone else early
KoratOP
Thanks a lot for the time brother
KoratOP
Hey @Ray one more thing it got into my mind is to ask if you use anything when doing client side queries like react query ?