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 get the form data into a simple object:
// inside api/registerForm/route.tsx
import { schema } from "@app/registrationSchema"
export async function POST(req: NextRequest) {
const formData = await req.formData(); // Get the form data
const data = Object.fromEntries(formData); // Convert form data into a simple data object
let parsed = schema.safeParse(data)
if (parsed.success) {
// Add parsed.data to the database
return NextResponse.json({ message: "User registered", data: parsed.data });
} else {
return NextResponse.json(
{ error: parsed.error },
{ status: 400 }
)
}
}
With these changes in place, we've created a registerForm endpoint which expects data to be posted in formData format instead of JSON.
Adjusting Our Registration Form
Inside of the RegistrationForm.tsx file, we'll need to make a few changes to the fetch request.
First we'll comment out the existing fetch request to the JSON register endpoint.
In its place we'll create a new FormData object and append the first, last, and email fields to it. Then we'll send the FormData object as the body of the request, without setting the Content-Type header:
// inside of RegistrationForm
const onSubmit = aysync (data: z.infer<typeof schema>) => {
const formData = new FormData(); // Create a new FormData object
formData.append("first", first)
formData.append("last", last)
formData.append("email", email)
fetch("/api/registerForm", {
method: "POST",
body: formData,
})
.then(response => response.json())
.then(data => console.log(data))
}
We don't need to send the Content-Type header, because FormData is the default format.
Testing the Form
Over on the page, we can hit submit and see the "User registered" message in the console!
This is the second method of sending form data to the server. In the next lesson, we'll discuss how to use server actions for submitting form data and performing server-side validation.