Forms 0 exercises
lesson

Creating an API Route for Form Data

Start by creating a new file at api/registerForm/route.tsx.

The code in this file will be mostly the same as in the register/route.tsx file, but with a couple of key differences.

This time w'll be using req.formData() inside of the POST request handler, and using Object.fromEntries() to g

Loading lesson

Transcript

00:00 Now I'm going to go create a new route here called register form, route.tsx. And in there, I'm going to bring the code from register is mostly the same, but now we've got back this form data object. That is a special object that has getters and setters on it.

00:19 We really want a simple object that has just the first, last, and email on it. So what we're going to do is use object at from entries to take that form data and convert it into a simple data object. And that's really it. So now we have this API register form endpoint,

00:39 and we just need to post to that in a form data format as opposed to a JSON format. So let's go back into our registration form and I will copy this section and then comment it out. So you still have it, but we're going to make some changes. We're going to say,

00:57 we want to go to register form and start to make some form data. So to do that, we create a new form data object, and then we just set the values individually. We just append first, last, and email to our form data. And then we can just send that as the body. Now what happens here to the content type? Well, we just get rid of it.

01:16 Form data is the default. All right, let's give it a try. And then let's hit submit. And there you go. User registered. Awesome. In the next section, we'll take a look at server actions and how to use them to go and submit form data and also validate it on the server side.