Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 43 ยท Views and Templating

Forms, Redirects and Flash Messages

Handle HTML forms in Express: parse urlencoded bodies, validate, use the POST-Redirect-GET pattern, override methods, and show flash messages from a session.

Forms are how most people send data to a server-rendered site: sign-up pages, search boxes, comment boxes. Handling them well takes more than reading req.body. If you answer a POST with a page, a reload resubmits the form and creates the order twice. If you redirect, the user has no idea whether it worked. The fix is a small, standard recipe: validate, redirect, then show a one-time message.

Real Express code here is read-only, because npm is not available in the browser. The runnable examples use our mini Express stand-in with hand-written stand-ins for the body parser, the session and the flash helper. Each one is labeled.

Reading form data

An HTML form with method="post" sends its fields as application/x-www-form-urlencoded, for example name=Mina&email=mina%40example.com. Express parses that with its built-in middleware:

JavaScript
app.use(express.urlencoded({ extended: false }));

app.post('/contact', (req, res) => {
  const { name, email } = req.body;
});

extended: false uses the simple parser, which is almost always what you want. In Express 5, req.body is undefined if no body parser matched the request, so guard with req.body ?? {} when a route can receive other content types. The built-in middleware lesson covers limits and JSON bodies.

A form can only send GET and POST. That is why it has no PUT or DELETE, which we deal with at the end.

The POST-Redirect-GET pattern

POST-Redirect-GET

  1. POST
The browser sends the form.
  1. Process
Validate and save on the server.
  1. Redirect
Answer 303 with a Location header.
  1. GET
The browser loads a normal page.

Reloading now repeats a harmless GET.

1 / 2

When the form is valid, do the work, then res.redirect(303, '/thanks'). Status 303 says "now fetch this other page with GET", and it is the most precise choice after a POST (a plain 302 works in practice too). When the form is invalid, do not redirect; render the form again with the typed values and error messages and an error status such as 422 Unprocessable Content, so the user does not have to retype everything.

JavaScript
app.post('/contact', (req, res) => {
  const errors = validate(req.body);
  if (Object.keys(errors).length > 0) {
    return res.status(422).render('contact', { errors, values: req.body });
  }
  saveMessage(req.body);
  req.flash('success', 'Thanks, we got your message.');
  res.redirect(303, '/contact');
});

Flash messages

After a redirect there is no way to hand the next request a message through the redirect itself. A flash message solves this: store the message in the user's session, show it on the next page, and delete it as it is read. Typically that uses express-session (see Sessions and Login) and a small helper:

JavaScript
import session from 'express-session';

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, sameSite: 'lax' },
}));

app.use((req, res, next) => {
  req.flash = (type, message) => {
    req.session.flash ??= {};
    if (message === undefined) {            // read and clear
      const list = req.session.flash[type] ?? [];
      delete req.session.flash[type];
      return list;
    }
    (req.session.flash[type] ??= []).push(message);
  };
  res.locals.flash = { success: req.flash('success'), error: req.flash('error') };
  next();
});

Copying the message into res.locals makes it available to every template, as in the template lesson. There are also packages (such as connect-flash) that provide the same helper.

A runnable form flow

The stand-in below combines four pieces written for this lesson: a body parser that reads the stream and splits the fields, a session kept in a Map and identified by a cookie, a flash helper, and a form route that validates and redirects. A small client plays the browser: it remembers the cookie and shows each step. Real express-session is more careful (signed cookies, stores, expiry), so treat this as an outline.

Node.js Validate, redirect, flash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the five lines in order. The invalid post keeps the typed name and returns 422. The valid post answers 303 with a Location header and an empty body. The next GET shows the flash message, and a reload shows it is gone, because reading it cleared it. A reload also cannot resubmit anything, since the last request was a GET.

Pages with forms that change data should also protect against cross-site request forgery (CSRF). Using SameSite=Lax cookies helps, and a CSRF token in a hidden field is the classic defense. See Security Best Practices.

Method override for PUT and DELETE

Browsers send only GET and POST from a form. A common trick is a form that posts with a marker, which a middleware turns into the real method before routing:

HTML
<form method="post" action="/notes/7?_method=DELETE">
  <button>Delete note</button>
</form>
JavaScript
import methodOverride from 'method-override';

app.use(methodOverride('_method'));   // reads ?_method=DELETE

app.delete('/notes/:id', (req, res) => {
  deleteNote(req.params.id);
  res.redirect(303, '/notes');
});

Only allow the override on POST requests and keep deletes behind a login. If your pages use JavaScript, fetch(url, { method: 'DELETE' }) avoids the trick entirely.

Node.js Method override, simplified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same POST reaches two different handlers depending on the marker, and the GET request is not rewritten, so it finds no route.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why redirect after a successful POST instead of rendering a page?

    After a redirect the browser is on a GET page, so a reload repeats a harmless GET instead of the POST.
  2. 2. Which status fits an invalid form that is shown again with errors?

    A 4xx status such as 422 signals that the submitted data was not accepted, while the body shows the form again.
  3. 3. Where does a flash message live between the redirect and the next page?

    The message is stored in the session, read on the next request and removed.
  4. 4. What does the Express 5 behavior "req.body is undefined" mean for form routes?

    Add express.urlencoded() before the route; otherwise req.body is undefined.

Summary

  • Parse form posts with express.urlencoded({ extended: false }).
  • Use POST-Redirect-GET: on success redirect with 303; on failure re-render with a 422.
  • Flash messages are session values read once, which keeps redirects informative.
  • Browsers only send GET and POST from forms; method-override or fetch covers the other verbs.
  • Forms that change data need CSRF protection.

Next: Designing a REST API in Express.