Contact Form - NodeJS MDB Pro component
Bootstrap 5 Contact Form with Node.js
This is a step-by-step guide tutorial on how to easily create beautiful contact forms using the Bootstrap framework, JavaScript and NodeJS environment with Express server. It also covers validation of data, sending requests using AJAX and other form related topics.
For creating Contact Forms using PHP environment please follow the link
Final code for the Contact Form with NodeJS Starter you can find inside
integrations
folder of the
MDB Advanced package
Prerequisites
Before starting the project make sure to install the following utilities:
- Node LTS environment (12.x.x recomennded)
- Express- setting the server
- Express-validator - for validating the form
- Nodemailer - for sending mails
- Multer - for handling multiparts request (reading FormData)
- Dotenv - for loading environment variables
- Cors - for enabling CORS (Cross-origin resource sharing)
Within this tutorial we are using the Material Design for Bootstrap library, you can download it for free from here. Without the library, the form will still work — however it may look and behave differently. It's recommended to use this library along with the tutorial.
Form HTML
First, create basic contact form which will be our base for validating and sending data.
Copy and paste the following HTML and JavaScript code into your file (e.g.
index.html
):
Rest of the frontend code for sending Contact Forms with NodeJS, such as validating form on frontend side or sending form with AJAX will be the same as in PHP Contact Form tutorial, therefore it will be discussed here only in NodeJS relate parts.
Create NodeJS server file
Create a new file called server.js
inside your application's root directory.
If you haven't installed the express, nodemailer, body-parser and other necessary packages from the npm repository so far, do so immediately using the following command in your application terminal:
Having all set up, let's create our server. Paste following code into your file
This will import all necessary dependencies, initialize application as express instance,
allows Cross-Origin Resource Sharing (CORS) for sending information between frontend and
backend development servers and finally start the server.
const upload = multer()
and app.use(upload.none())
creates
middlewarae for handling multiparts requests, which will allow to send contact form data using
FormData object.
In this example we use app.use(upload.none())
to show how multipart request can
be handled (with file upload turned off), however it is not recommended to use it global
scope. In your production app use e.g. upload.any()
for specific endpoints in
which you expect to handle multipart requests.
Create file structure for mail sending server
Having the server set up you are ready to create a file structure for mail sending route and middleware. For the purposes of our course, it is not necessary, but in case you want to expand the functionality of our example, it is worth knowing what the file structure could looks like in applications using the NodeJS environment and Express server.
Create and read environment variables file
Firstly, create .env
file inside your root directory. This file will contain
all your private data used inside your NodeJS project. It's content for our purposes would
look like this:
Example .env
file for Gmail SMTP
Please note that we are using SMTP for Gmail here. If you would like to use another provider
your HOST, PORT and PROVIDER
would be different. Also if you would like to send
test mails in development mode you may want to be interested in fake SMTP servers, e.g.
Mailtrap. Also for production purposes it
is recommended to use one of many SMTP providers.
Never publish your environment variable files. Include all your
.env
files inside .gitignore
file when you publish your code.
Now add /config/index.js
file that will read all your environment variables.
... and change your server.js
file so the config can expose your variables to
the server:
Also notice that we added app.use("/api", routes);
which will use our router
from the next section.
Create router and contact form routes.
Create /routes
folder and inside it create two files. First
index.js
that will control all your project routes:
... and contact.routes.js
file that will contain all your contact form related
routes.
Thanks to express.Router({ mergeParams: true })
we can access the
params
from the parent router inside the child router. In our case creating
router.post('/', ...)
is equal to router.post('/contact', ...)
.
This structure is very helpful in deep nested routes structure.
Our contact router is also using sendContactForm
method from the
contactController. Let's create this file.
Contact controller
Controllers are callbacks passed to the router methods which process request to the route and generate the response.
Create /controllers
folder inside which you will create
contact.controllers.js
file. Controller for /contact
route will
look as follows:
Controller is based on a class instance for better scalability of the application. You could also use function based controller aswell.
Line 5 - const transporter = nodemailer.createTransport({ })
is used to create
a function that takes the object containing the configuration of the transporter as a
parameter. It is in this configuration that you define the host from which emails are sent
port, authorization, and many other settings that are to be sent.
Line 14 - create class instance of the controller that, in this example will take request and response from the rserver as its constructor arguments.
Line 20 - declares sendContactForm
method for handling POST
method
on /contact
route.
Lines 22-33 - defines the mailOptions
object that is sent to the sendMail()
method of transporter. It is in this object that we define, to who the email is to be sent,
from who, what is its subject, text, and to who the response in the email is to be
addressed. In this object are many more options that you can use. You will find them
here.
Lines 35-48 - Code responsible for sending the mail with the parameters defined inside
mailOptions
. Will send either success or failure response message to the
frontend.
Create validating middleware
Middlewares are functions that have access to the server request and response objects. In our example we will create middleware function that will validate contact form data.
Create /middleware
folder and inside it create validate.js
file.
We are using here express-validator
package that will help us validate
request.body
and if something is wrong provide server response with proper
error message. If everything in the request is ok, next()
function that will
allow server to call next function (controller) is called.
Now update contact.routes.js
file with our validator. Note that middleware
function is added between the route and controller callback.
Run server
In your package.json
file add script that will run your server:
You can also add start:dev
script for development purposes that will restart
your server anytime you make a change to the code. For that add nodemon
package
to your application.
Connect frontend form with backend server
To connect frontend contact form with backend server we will use AJAX.
Now it's time for you to run your backend server and frontend application and start sending your contact forms.
Informations provided above are just an example of implementation of sending contact forms using NodeJS server. If you have any questions, please do not hesitate to post a question on our support forum.