Skip to content

Handling forms in Express

New Course Coming Soon:

Get Really Good at Git

How to process forms using Express

This is an example of an HTML form:

<form method="POST" action="/submit-form">
  <input type="text" name="username" />
  <input type="submit" />
</form>

When the user presses the submit button, the browser will automatically make a POST request to the /submit-form URL on the same origin of the page. The browser sends the data contained, encoded as application/x-www-form-urlencoded. In this particular example, the form data contains the username input field value.

Forms can also send data using the GET method, but the vast majority of the forms you’ll build will use POST.

The form data will be sent in the POST request body.

To extract it, you will need to use the express.urlencoded() middleware:

const express = require('express')
const app = express()

app.use(express.urlencoded({
  extended: true
}))

Now, you need to create a POST endpoint on the /submit-form route, and any data will be available on Request.body:

app.post('/submit-form', (req, res) => {
  const username = req.body.username
  //...
  res.end()
})

Don’t forget to validate the data before using it, using express-validator.

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. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Express.js Handbook
→ Read my Express.js Tutorial on The Valley of Code

Here is how can I help you: