Node js Express Insert Data From Form into MySQL DB Tutorial

Node js Express Insert Data From Form into MySQL DB Tutorial

In this tutorial, you will learn store data from HTML form to MySQL database in Node JS Express app.

How to Insert Form Data in MySQL using Node js Express

Simply create the form in HTML and create a route to send the data to the app server, then connect the app server to the database and store the data through a Node JS Express project using MySQL insert into clause queries:

Step 1 – Create Node Express js App

To create a Node JS Express project directory run the command mkdir my-app && cd my-app on a CMD or terminal window:

mkdir my-app
cd my-app

Next run npm init -y to initialize a project and create a package. json file:

npm init -y

Step 2 – Create Table in MySQL Database

To create the database and table for your Node Express JS project, simply run the following SQL query for the same:

CREATE TABLE `contacts` (
  `f_name` varchar(100) NOT NULL,
  `l_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `message` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)

Step 3 – Install express flash ejs body-parser mysql Modules

To install some required dependencies like express flash ejs body-parser mysql dependencies: For node express js project, just use the following command on cmd or terminal window for the same:

npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install mysql --save

Step 4 – Create HTML Markup Form

Go to views directory, and create index.ejs file inside it, and then create html form to send data on server for insertion into it to the database:

<!DOCTYPE html>
<html lang="en">
    <title>Node.js Express Save Data from Html Form to Mysql Database -</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <div class="container mt-4">
      <div class="card">
        <div class="card-body">
          <% if (messages.success) { %>
              <p class="alert alert-success m2-4 mb-2"><%- messages.success %></p>
          <% } %>  
          <h2>Node.js Express Save Data from Html Form to Mysql Database -</h2>
          <form action="contact-us" method="POST">
            <div class="form-group">
              <label for="firstName">First Name</label>
              <input type="text" class="form-control col-lg-9" id="f_name" aria-describedby="emailHelp" placeholder="Enter first name" name="f_name">
            <div class="form-group">
              <label for="lastName">Last Name</label>
              <input type="text" class="form-control col-lg-9" id="l_name" aria-describedby="emailHelp" placeholder="Enter last name" name="l_name">
            <div class="form-group">
              <label for="exampleInputEmail1">Email address</label>
              <input type="email" class="form-control col-lg-9" id="exampleInputEmail1" aria-describedby="emailHelp" name="email" placeholder="Enter email">
            <div class="form-group">
              <label for="exampleInputEmail1">Message</label>
              <textarea name="message" class="form-control col-lg-9"></textarea>
            <button type="submit" class="btn btn-primary">Submit</button>

Step 5 – Create Database Configuration File

Create database.js file and add the following code into it to connect your app to db:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'test' // // Replace with your database Name
conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
module.exports = conn;

Step 6 – Create Routes in App.js

Open app.js and create routes for showing forms and storing data to MySQL database:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var db=require('./database');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
/* GET home page. */
app.get('/', function(req, res, next) {
  res.render('contact-us', { title: 'Contact-Us' });
});'/contact-us', function(req, res, next) {
  var f_name = req.body.f_name;
  var l_name = req.body.l_name;
  var email =;
  var message = req.body.message;
  var sql = `INSERT INTO contacts (f_name, l_name, email, message, created_at) VALUES ("${f_name}", "${l_name}", "${email}", "${message}", NOW())`;
  db.query(sql, function(err, result) {
    if (err) throw err;
    console.log('record inserted');
    req.flash('success', 'Data added successfully!');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error ='env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
module.exports = app;

Step 6 – Start App Server

You can use the following command to start node js app server:

//run the below command

npm start

after run this command open your browser and hit


Store data from html form into MySQL database in node js express app; In this tutorial,you have learned how to insert data contact us from data into MySQL database using node js express app.

Recommended Node JS Tutorials


Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Node js Express Insert Data From Form into MySQL DB Tutorial

  1. Hey, Thanks for making this blog it was very helpful, But what is that contact-us path that you have used in form action and some .render and .get functions. Can you Please clarify that.

Leave a Reply

Your email address will not be published. Required fields are marked *