Forms 101: Receiving the form data

Let’s now handle receiving the form data.

The simplest way I know to test this is by creating a simple Astro site with server-side rendering enabled.

Create an empty Astro site using

npm create astro@latest

Now go in the folder and install the Node.js adapter with

npx astro add node

This changed the astro.config.mjs configuration to:

import { defineConfig } from 'astro/config'

import node from '@astrojs/node'

// https://astro.build/config
export default defineConfig({
  output: 'server',
  adapter: node({
    mode: 'standalone',
  }),
})

Run npm run dev to start the Astro site.

Now go to src/pages/index.astro and add the form to the body:

<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <link rel='icon' type='image/svg+xml' href='/favicon.svg' />
    <meta name='viewport' content='width=device-width' />
    <meta name='generator' content={Astro.generator} />
    <title>Astro</title>
  </head>
  <body>
    <form method='post'>
      <input type='text' name='city' />
    </form>
  </body>
</html>

This should be what you see in the browser:

To handle the server-side data, now we add some JavaScript code to the frontmatter of the component, which is something Astro-specific and basically where code runs server-side when we hit the page endpoint /:

---

---

<html lang='en'>
  ...
</html>

Inside it, we can handle a POST request using:

---
if (Astro.request.method === 'POST') {

}
---

<html lang='en'>
  ...
</html>

and when we do so, we can now access the form data calling the formData() method on the Request object, which is available in this case through Astro.request:

---
if (Astro.request.method === 'POST') {
  const data = await Astro.request.formData()
}
---

<html lang='en'>
  ...
</html>

(we have to use await because calling formData() returns a promise).

This is all standard Web APIs: Request, FormData.

Now we can access individual data using data.get():

---
if (Astro.request.method === 'POST') {
  const data = await Astro.request.formData()
  const city = data.get('city')
  console.log(city)
}
---

<html lang='en'>
  ...
</html>

FormData provides many other methods, see the full list on MDN.

Try it! You should see the data entered in the input field printed to the terminal running npm run dev.

Lessons in this unit:

0: Introduction
1: Creating a form
2: Submitting a form
3: ▶︎ Receiving the form data
4: Form validation
5: More tags useful in forms
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!