W3cubDocs

/Astro

Build HTML Forms in Astro Pages

In SSR mode, Astro pages can both display and handle forms. In this recipe, you’ll use a standard HTML form to submit data to the server. Your frontmatter script will handle the data on the server, sending no JavaScript to the client.

Prerequisites

  • A project with SSR (output: 'server') enabled

Recipe

  1. Create or identify a .astro page which will contain your form and your handling code. For example, you could add a registration page:

    src/pages/register.astro
  2. Add a <form> tag with some inputs to the page. 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.

    src/pages/register.astro
  3. Use validation attributes to provide basic client-side validation that works even if JavaScript is disabled.

    In this example,

    • required prevents form submission until the field is filled.
    • minlength sets a minimum required length for the input text.
    • type="email" also introduces validation that will only accept a valid email format.
    src/pages/register.astro
  4. The form submission will cause the browser to request the page again. Change the form’s data transfer method to POST to send the form data as part of the Request body, rather than as URL parameters.

    src/pages/register.astro
  5. Check for the POST method in the frontmatter and access the form data using Astro.request.formData(). Wrap this in a try ... catch block to handle cases when the POST request wasn’t sent by a form and the formData is invalid.

    src/pages/register.astro
  6. Validate the form data on the server. This should include the same validation done on the client to prevent malicious submissions to your endpoint and to support the rare legacy browser that doesn’t have form validation.

    It can also include validation that can’t be done on the client. For example, this example checks if the email is already in the database.

    Error messages can be sent back to the client by storing them in an errors object and accessing it in the template.

    src/pages/register.astro

More recipes

© 2021 Fred K. Schott
Licensed under the MIT License.
https://docs.astro.build/en/recipes/build-forms/