The developer creates a reusable wrapper for the fetch function in a Next.js application to handle JSON-formatted POST requests consistently. The process includes refactoring existing server actions to use this new utility, configuring custom headers, and ensuring proper form data processing before testing the implementation in the UI.
Length 5:20
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #next.js #typescript #fetch #api #server actions #web development #programming #json #coding #software engineering
0:00 Now, before we go ahead and implement authentication on our 0:03 Next.js 0:05 application, 0:06 I wanna go ahead and implement a common global wrapper around our 0:10 existing fetch function. 0:13 So in our server actions, for example, in our 0:17 sign up component, we have the create user server action 0:21 which 0:21 is utilizing the Node.js fetch function to make a network 0:25 request to our Nest.js backend. Now, there's common functionality 0:29 I want to introduce into all fetch calls we make to our backend, 0:33 therefore, I wanna introduce a wrapper around this 0:36 fetch function 0:38 so we can apply this common behavior to all fetch calls 0:42 and not have to duplicate it. 0:44 So let's go ahead in our util folder and create a new 0:48 fetch, and create a new fetch.ts 0:52 file. Now, right now we only have post requests 0:55 that we're 0:56 making to our server, so I wanna go ahead and wrap post requests 0:59 with their common functionality first. 1:02 I wanna make sure that when we send post requests to our server 1:05 with data, 1:06 we're not utilizing form data and not sending this to the server with a 1:10 form 1:10 data header. Instead, I want to send this just as regular 1:14 JSON just like we do in Postman. So in order to make this happen, 1:18 we need to set the application JSON content type on 1:22 all of these post requests, 1:24 as well as parse our JSON body appropriately 1:29 from this form data. So let's go ahead and export a 1:32 const called post that will take in the 1:36 actual path that we're trying to reach on our 1:40 API. So that's gonna be everything after the 1:43 API URL. 1:45 And then secondly, I wanna take in the form data 1:48 that we know our 1:49 forms in Next.js will be submitting to these server 1:52 actions. So now what I'll do is I'll simply copy the
The rest of the transcript is for members.
Sign in