Next.js Discord

Discord Forum

Server Action fetch

Answered
bscdev#1145 posted this in #help-forum
Open in Discord
Hi All,
When we create and upadate database using external backend api , Do we need to use fetch in the server action function.
Or we should directly use fetch in the client side. Which way will improve performance? Please advise.
Thanks
Answered by Arinji
ok so @bscdev#1145 i spoke with joulev
https://discord.com/channels/752553802359505017/766433464055496744/1245694637335773185

Sorry for the whole actions stuff.
but yea, just use a server action for mutations. Just dont use a server action as a replacement for server components, aka purely data fetching.
View full answer

91 Replies

@bscdev#1145 why are you fetching from server actions or client components, you are meant to fetch in a server component
if you are making a post request, you can make a server action and call it from a client component


but get requests are done with a server component
@Arinji , Thanks for your reply. When I am making a post/put request to an external backend api ,I make a server action to handle it. But When I am making an GET request , I am using client component with react query to handle it with loading effect, caching etc. I know nextjs fetch has its own caching . I tried also to fetch a GET request in server component , But imagine a case where your externer api is down in that case how do you handle the situtation because fetching in server component is instatnt. Please put your opinion.
server actions expose POST endpoints
you are doing a GET request through a POST endpoint
that is wrong
so just make a get route handler, and fetch it from a client component
but only do this if you have to do it with no other method
I making different routes and end points for GET, POST and PUT. I am fetching GET request from a client component. But when I am making a POST and PUT request I use server actions. I am just asking is it a right practise.
yes, that is a correct practice.
wait actually
Thank You so much
only do POST with actions
@Arinji server actions expose POST endpoints
this is the reason
makes sense?
so PUT, GET, PATCH.. all of those are route handlers
POST is a server action (or route handler if you want)
Yes that makes sense . You mean use server actions for POST or PUT requestes. right?
ok
np, mark a soln if your question got resolved
Original message was deleted
,
@Arinji https://122:301:120:9:8000/api/v1/auth/signup-session is my external backend api responsible to create signup and I want to send data to this api via POST request from client side, I handle this using a server actions fetch method in nextjs side https://122:301:120:9:8000/api/v1/user/profile-update is is my external backend api responsible to update profile and I want to update data to this api via PUT request from client side , I handle this I handle this using a server actions fetch method in nextjs side. https://122:301:120:9:8000/api/v1/user/profile is a GET route handler , I am calling it from nextjs end via fetch method in a client component in order to handle loading, cahching etc.
1st and 3rd are correct
2nd is wrong, dont use this server actions for PUT requests
use a PUT route handler
already mentioned that
So Do I need to make a PUT request from a client component without any server actions
https://122:301:120:9:8000/api/v1/user/profile-update this is my PUT route handler , from where should I call it in nextjs side using server actions or directly from client component.
OK . thanks. If you have time then I am very curious to know why we should not handle a PUT request with a server action. Thank you in advance.However I understood the concept , I will follow it.
if you are calling a server action, which itself is a post request.. you arre just doing a post request calling a put request
it messes with caching
OK I got it.
Thank You
Hello @Arinji , I repoened this question forum since I am facing an issue. Acctording to you I am calling a backend PUT route handler api from my frontend nextjs client component via fetch method results a CORS error. However my backend is CORS enabled. When I called this backend api from nextjs api router as well as using server actions , it works fine. That means , Nextjs client component blocks PUT, PATCH,POST requests. But you told me in your above recommendation to execute a PUT request from nextjs client component.Could you please share me the code if you try the same in some of your application?
i mean, your PUT requests will have cors errors if you just call a different domain :D
what is your backend hosted on?
backend is hosted in different domain
like is it built with nextjs? or something express related
No backend is writen in nodejs and it is separate from nextjs frontend
ok, can you show your cors code?
My nextjs fronend and nodejs backend are mounted in different domain.
like where you specify the cors headers
yes I will
wait a min
Also just to clarify, the reason it works from a server action, is because on the server there is no cors. Cors exists on the browser only
so its not a nextjs specific thing
btw @bscdev#1145 type this pls
res.setHeader('Access-Control-Allow-Credentials', "true") res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, PUT')
/remove-post-answer 
do you have an options route setup in your backend?
yes you are right. But I have put here my origin res.setHeader('Access-Control-Allow-Origin', 'https:.//website.com') and call it from client component then also fetch gives a CORS error
Yes
no so like, how cors works is that it first makes a request to the options route to get the cors headers
But I can call it from nextjs server component as well
I know server does not have CORS.....But could you advise me what kind of header I should set
one sec
Sure
which backend are you using? like framework
express
ok so do you have the cors middleware proxy setup?
I have CORS middleware but when I was getting a cors error , I also put res.setheader(....)
ok can you show your middleware
the app.use part specifically
ok just to check, can you add this to your express app
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', "true")
  res.header('Access-Control-Allow-Methods', 'OPTIONS, PUT')
  next();
});
app.use(cors())
actually I put this headers to route handlers. But now I will try your way.
ok I will try it and let you know the outcome....Thanks for helping me.
I have following code in nextjs client component await fetch(${process.env.NEXT_PUBLIC_APIURL}/api/v1/users/profile-update, { method: 'PUT', headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": Bearer ${session.token} }, body: JSON.stringify({ username, email, phone, }) })
I will let you know soon , after I create a cors middleware.Thanks
@Arinji if you are calling a server action, which itself is a post request.. you arre just doing a post request calling a put request
nothing wrong. making mutation requests inside a server action to an external backend is normal. same way you do a GET fetch(...) in server component.
i thought it was a nextjs backend on the same domain
@Arinji i thought it was a nextjs backend on the same domain
in that case the recommendation is to ditch the PUT handler and put its logic inside the server action. how did it become ditching server actions
@joulev in that case the recommendation is to ditch the PUT handler and put its logic inside the server action. how did it become ditching server actions
I thought OP wanted a PUT handler lol, so i just told him to call it from a client component xD,
i asked alfon when i saw he mentioned the diff domain backend, and i was gonna tell him to use a server action if the cors middleware didnt work
I see now i shld have checked if it was an external backend or not, but i dont see anything wrong with fetching a PUT request from a client component, since PUT is just a modification
ok so @bscdev#1145 i spoke with joulev
https://discord.com/channels/752553802359505017/766433464055496744/1245694637335773185

Sorry for the whole actions stuff.
but yea, just use a server action for mutations. Just dont use a server action as a replacement for server components, aka purely data fetching.
Answer
Thanks @Arinji @joulev for helping me out . Since My backend is mounted in a different domain. I usually use server actions for mutations. I wanted set rules for myself, that's why I initiated this question to make sure whether my understanding is correct. Nextjs blocks by giving a CORS error if a mutation request triggers to a backend api(different domain) or third party api(shopify etc) from a client component with a "use client" directive. I just wanted to know is it a natural behavior of a nextjs client component. However, I am using a server action for a mutation request. Thanks.
noted.Thank you so much.
Original message was deleted
That’s not an answer
@joulev , Actually I am using chrome and My backend api has set with cors middleware which can accpet mutation request from nextjs server actions, nextjs server component. It blocks from nextjs client component by giving a cors error. I checked microsoft edge and other browser also, getting same error. below is my backend cors middleware code. My backend is mounted in domain http://localhost:80000 export const corsMiddleware = async(request, response, next) => { response.setHeader('vary', 'Origin') response.setHeader('Access-Control-Allow-Origin', '*') response.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization') response.setHeader("Content-Type", "application/json"); response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT, DELETE') response.setHeader('Access-Control-Allow-Credentials', "true") next(); } router.use('/profile-update', corsMiddleware())
I know It. Other middlewares are working fine with the same configuration. Like auth middleware etc.
I have no idea what type of more headers I need to set in cors middleware function.