Handling forms in Express

By

Published · Updated

Tagged: Express.js

Learn how to process form submissions in Express, reading POST data with the express.urlencoded() middleware and accessing fields on req.body.

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.

The request body looks like this:

username=flavio

Each field is sent as name=value, joined with &. Only fields with a name attribute are sent.

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

Parse the body with express.urlencoded()

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())

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

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

Add the middleware before your routes. Middleware runs in order, so a route defined above app.use(express.urlencoded()) sees an unparsed body.

req.body is undefined

This is the most common problem. In Express 5, req.body is undefined until a body parser fills it. In Express 4 it was an empty object {}.

So if you forget the middleware, or add it after the route, req.body.username throws:

TypeError: Cannot read properties of undefined (reading 'username')

The urlencoded parser also leaves req.body as undefined when the request’s Content-Type isn’t application/x-www-form-urlencoded. That happens in two common cases:

The extended option

express.urlencoded() takes an extended option. In Express 5 it defaults to false, and older tutorials (including an earlier version of this post) set it to true.

With extended: false, field names are taken as they are:

user[name]=tobi  →  { 'user[name]': 'tobi' }

With extended: true, Express uses the qs library, which turns brackets into nested objects:

app.use(express.urlencoded({ extended: true }))
user[name]=tobi  →  { user: { name: 'tobi' } }

For a flat form like a login or contact form, the default is fine. Use extended: true only if you name your fields with brackets to get nested data.

What the values look like

A few things that surprise people:

Validate the data

req.body is built from what the user sent, so treat every value as untrusted. Anyone can send a request with any fields, not just your form.

Here’s a basic check:

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

  if (typeof username !== 'string' || username.trim() === '') {
    return res.status(400).send('Username is required')
  }

  // save the data...
  res.redirect(303, '/thanks')
})

The typeof check matters: as we saw, a field sent twice arrives as an array, and calling string methods on it would crash your route.

For real forms with many fields, use a library. I show how in validating input in Express using express-validator.

Redirect after a successful POST

After you handle the form, redirect to another page instead of rendering a response directly. If you render, and the user refreshes, the browser asks to submit the form again, and you might save the data twice.

res.redirect(303, '/thanks') tells the browser to load /thanks with a GET, so a refresh is harmless.

Size limit

By default express.urlencoded() accepts bodies up to 100kb. A bigger body is rejected with a 413 error (entity.too.large). That’s plenty for text forms. If you have a big textarea, raise it:

app.use(express.urlencoded({ limit: '1mb' }))

There’s also a parameterLimit option, 1000 fields by default.

GET forms

If your form uses method="GET", like a search box, the data is not in the body. It’s added to the URL as a query string (/search?q=express), and you read it from req.query:

app.get('/search', (req, res) => {
  const q = req.query.q
  //...
})

No middleware needed for that.

Want me to talk about your product? You can sponsor this site.

Related posts about express: