In this Tutorial ->

Handling forms is a fundamental aspect of web development. In this tutorial, we will explore how to handle forms efficiently in Express, a popular Node.js web framework. We will cover essential concepts such as form submission, data validation, error handling. By the end of this tutorial, you will have a solid understanding of how to build robust and user-friendly forms in Express. Let’s Start
Setting up Express Project
1. Create a new directory for your project and navigate to it in your terminal:
mkdir express-app
cd express-app
2. Initialize a new npm project by running the following command and following the prompts:
npm init
3. Install Express as a dependency:
npm install express
4. Create a file named app.js (or any other preferred name) in the project directory. This will be the entry point of your Express application.
5. Open app.js in a code editor and add the following code to set up a basic Express application:
// Import the required modules
const express = require('express');
const app = express();
const port = 3000; // Choose your preferred port number
// Set up a route for the homepage
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
6. Save the file and go back to your terminal.
7. To start the Express application, run the following command:
node app.js
Once the server is up and running, you will see following message in the console:
‘Server is running on port 3000’
Open your web browser and visit http://localhost:3000 (replace 3000 with the port number you chose in the code). You should see the message “Hello, Express!” displayed in the browser.

You can stop this server by pressing CTRL+C.
Creating a Basic Form
To handle form submissions in Express, you first need to create a basic HTML form that users can interact with. Here’s an example of how to create a basic form using HTML:
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
In this example, we have a simple form that collects the user’s name and email address. The form’s action attribute is set to “/submit”, which represents the route in Express that will handle the form submission. The method attribute is set to “POST” to indicate that the form data should be sent as a POST request.
Make sure to include appropriate input fields and labels for the form fields you require. Use the name attribute on input fields to identify them when handling the form submission.
We want this form to be displayed as our homepage ie localhost:3000.
Next, let’s move on to handling the form submission in Express.
Handling Form Submission
When working with forms in Express, it is essential to handle form submissions properly. This involves defining a route to handle the form submission request, extracting the form data, and implementing the necessary logic to process and respond to the submitted data.
To handle form submissions in Express, follow these steps:
a. Define the Route: Start by defining a route in your Express application that corresponds to the form’s action attribute. This route should handle the HTTP POST request sent when the form is submitted. For example:
app.post('/submit', (req, res) => {
// Handle form submission logic here
});
In this example, the route is /submit, but you can choose any URL path that suits your application’s requirements.
b. Extract the Form Data: To access the submitted form data, you need to use middleware to parse the request body. One popular middleware for this purpose is body-parser. Install it by running the following command:
npm install body-parser
Once installed, import and use the middleware in your Express application:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
The urlencoded method of body-parser parses the form data sent in the request body and makes it accessible via the req.body object.
The extended: false option in the bodyParser.urlencoded() middleware configuration determines how the request body data is parsed.
When extended is set to false, the body-parser middleware uses the built-in querystring library to parse the URL-encoded data in the request body. This parsing mode treats the data as a nested object or array format.
For example, with extended: false, the URL-encoded form data:
name=John&age=30
will be parsed into an object:
{ name: 'John', age: '30' }
Setting extended to true would enable parsing of more complex data structures, such as arrays and objects nested within the form data.
However, for most use cases, setting extended: false is sufficient, as it covers the common scenario of processing simple form submissions with key-value pairs.
c. Implement the Form Submission Logic:
Inside the route handler for form submission (/submit in this example), you can access the form data using req.body. Process the form data according to your application’s requirements. For instance, you can perform database operations, send emails, or perform any other necessary actions.
Here’s an example of handling a form submission and logging the submitted data:
app.post('/submit', (req, res) => {
const name = req.body.name;
const email = req.body.email;
// Process the form data
console.log(`Submitted Name: ${name}`);
console.log(`Submitted Email: ${email}`);
// Send a response to the client
res.send('Form submitted successfully!');
});
In this example, the form data is extracted from req.body, and the name and email fields are logged to the console. You can replace the console logs with your custom logic.
d. Respond to the Client: After processing the form data, you can send a response back to the client to acknowledge the successful submission or provide any additional information. Use the res.send() method to send a response to the client.
For example, the code snippet above sends the response message “Form submitted successfully!” back to the client.
To ensure that we are on same page, here are some inputs
Folder Structure

app.js
// Import the required modules
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const port = 3000; // Choose your preferred port number
app.use(bodyParser.urlencoded({ extended: false }));
// Set up a route for the homepage
// we want the form to be displayed on home page
app.get('/', (req, res) => {
res.sendFile(__dirname+'/views/form.html'); // we use sendFile to display the html page.
});
// Set up route for form submission
app.post('/submit', (req, res) => {
const name = req.body.name;
const email = req.body.email;
// Process the form data
console.log(`Submitted Name: ${name}`);
console.log(`Submitted Email: ${email}`);
// Send a response to the client
res.send('Form submitted successfully!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
form.html
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
By following these steps, you can effectively handle form submissions in your Express application. Remember to customize the form submission logic to suit your specific requirements, such as storing data in a database or triggering certain actions based on the submitted form data.
Starting the Application
a. Open your terminal and run following command
node app.js
You will see following message in the console: Server is running on port 3000
Note – Please make sure that you have installed html module as well via npm.
b. Open your browser and navigate to http://localhost:3000/. You will see the content of form.html is being displayed on that page.

c. Enter the details as per your wish.

d. Click on submit. Once you submit this form, a post request ( as in form.html we have defined form method as post) will be sent to ‘/submit’ route which will then do the needful.

e. See the terminal to check whether you were able to catch those values.

That’s all.
Keywords to search for: Express form handling tutorial, Handling forms in Express.js,
Form submission with Express, Express form validation, Handling form data in Express, Express form handling best practices, Express form handling middleware, Handling file uploads in Express forms, Client-side form validation with Express,Express form handling examples, Express form handling tutorial, Handling HTML forms in Express.js, Form validation with Express, Handling form submission in Express, Express form handling best practices, Client-side form validation with Express, Express form data processing, Dynamic forms with Express.js, File uploads with Express forms, Redirecting after form submission in Express,
