@fastify/formbody

Parse application/x-www-form-urlencoded

@fastify/formbody

Parse classic URL-encoded form posts from HTML forms into request.body objects, for apps that still render server-side forms.

4 min read Level 1/5 #fastify#forms#parsing
What you'll learn
  • Install @fastify/formbody
  • Register the plugin
  • Read URL-encoded bodies from request.body

Fastify ships with a JSON body parser by default. For server-rendered apps with HTML forms, you also need application/x-www-form-urlencoded — the format browsers send when a form posts without enctype.

Install & Register

npm install @fastify/formbody
import formbody from '@fastify/formbody'

await app.register(formbody)

That is all you need. Fastify will now route requests with that Content-Type to the formbody parser.

A Login Form

type LoginBody = { email: string; password: string }

app.post<{ Body: LoginBody }>('/login', async (req, reply) => {
  const { email, password } = req.body
  // ... look up the user, verify, set session ...
  return reply.redirect('/dashboard')
})

The matching HTML form:

const html = `
  <form method="POST" action="/login">
    <input name="email" type="email" required />
    <input name="password" type="password" required />
    <button>Sign in</button>
  </form>
`

Combine With JSON

You can keep both parsers active and let Fastify pick by Content-Type:

await app.register(formbody)
// JSON is built in; no plugin needed.

app.post<{ Body: { email: string } }>('/subscribe', async (req) => {
  return { received: req.body.email }
})

The same handler now serves browser form posts and JSON API calls.

@fastify/http-proxy →