Skip to content

astro

Build forms with API routes

Astro

Build forms with API routes

Build forms with API routes

An HTML form causes the browser to refresh the page or navigate to a new one. To send form data to an API endpoint instead, you must intercept the form submission using JavaScript.

This recipe shows you how to send form data to an API endpoint and handle that data.

Prerequisites

Recipe

1. Create a `POST` API endpoint at `/api/feedback` that will receive the form data. Use `request.formData()` to process it. Be sure to validate the form values before you use them.
This example sends a JSON object with a message back to the client.

```ts title="src/pages/api/feedback.ts" "request.formData()" "post"
export const prerender = false; // Not needed in 'server' mode
import type { APIRoute } from "astro";

export const POST: APIRoute = async ({ request }) => {
  const data = await request.formData();
  const name = data.get("name");
  const email = data.get("email");
  const message = data.get("message");
  // Validate the data - you'll probably want to do more than this
  if (!name || !email || !message) {
    return new Response(
      JSON.stringify({
        message: "Missing required fields",
      }),
      { status: 400 }
    );
  }
  // Do something with the data, then return a success response
  return new Response(
    JSON.stringify({
      message: "Success!"
    }),
    { status: 200 }
  );
};
```
  1. Create a form component using your UI framework. Each input should have a name attribute that describes the value of that input.

    Be sure to include a <button> or <input type="submit"> element to submit the form.

    ```tsx title="src/components/FeedbackForm.tsx" export default function Form() { return (