Part 3 - Building a Full Stack Contact Form: Deployment 2023
Tags: webdev, tutorial, deployment, fullstack
Published: 2023-08-20 01:29:59

Welcome to Part 3 of our comprehensive full-stack contact form series! In this installment, your final dive will go into the deployment, taking the impressive groundwork you've laid so far and transforming it into a fully functional and hosted communication tool online.

### Contents

- [Preparing for Deployment](#Part-3:-Preparing-for-Deployment)
  - [Backend Enhancement: Transitioning to HTTPS](#Backend-Enhancement:-Transitioning-to-HTTPS)
  - [Frontend Refinement: Transitioning to HTTPS and Production Build](#Frontend-Refinement:-Transitioning-to-HTTPS)
- [Deployment: GitHub and CyberPanel](#Deployment:-GitHub-and-CyberPanel)
  - [Backend Deployment](#Backend-Deployment)
    - [Keeping the Backend Server Running: PM2](#Keeping-the-Backend-Server-Running)
  - [Frontend Deployment](#Frontend-Deployment)
- [Troubleshooting](#Troubleshooting)
- [Conclusion](#Conclusion)

<a id="Part-3:-Preparing-for-Deployment"></a>

## Preparing for Deployment

In this phase, we'll be focusing on the crucial steps to get your contact form ready for deployment. This will involve making the necessary adjustments, including the conversion of your backend from HTTP to HTTPS to ensure seamless POST requests.

<a id="Backend-Enhancement:-Transitioning-to-HTTPS"></a>

### Backend Enhancement: Transitioning to HTTPS

In order to ensure secure communication between your frontend and backend, it's important to convert your backend from using HTTP to HTTPS. This transition guarantees the secure transfer of data through your full-stack contact form. SSL certificates will be needed to complete this part.

**Resource and Reference:** A valuable resource that provides detailed insights into configuring SSL certificates for Node.js HTTPS can be found at [https://adamtheautomator.com/https-nodejs/](https://adamtheautomator.com/https-nodejs/)

1. **Install HTTPS Package:** Start by installing the https package using the following command in your terminal:

```
npm i https
```

2. **Import HTTPS Module:** At the top of your server.js file, import the https module as follows:

```
const https = require('https');
```

3. **Update Server Creation:** Modify the server creation process. You'll now create an HTTPS server instance using the **https.createServer** method which will replace the **app.listen** method going forward. This involves specifying the paths to your SSL certificate and private key files.

```
const httpsServer = https.createServer(
	{
		key: fs.readFileSync(
			'path-to-privkey.pem'
		),
		cert: fs.readFileSync(
			'path-to-cert.pem'
		),
	},
	app
);

httpsServer.listen(serverPort, () =>
	console.log(`backend is running on port ${serverPort}`)
);
```

Don't forget to comment out or remove the **app.listen** line.

With these updates, your backend is now transitioned to use HTTPS. In the next step, we'll make a small change in the frontend to ensure that the fetch URL points to the HTTPS backend, completing the circle of secure communication between your frontend and backend.

<a id="Frontend-Refinement:-Transitioning-to-HTTPS"></a>

### Frontend Refinement: Transitioning to HTTPS and Production Build

- **HTTPS**: The HyperText Transfer Protocol Secure (HTTPS) guarantees secure data exchange over the internet by encrypting information exchanged between the server and the client. ==HTTPS will be used and discussed in part 3 of the series before deployment.==

With the backend now utilizing HTTPS for secure communication, it's essential to ensure that the frontend also points to the updated secure API endpoint. Let's make this crucial update:

1. **Update API Endpoint URLs:** Open your frontend codebase and find the sections where you make API calls to the backend. If you've transitioned your backend to use HTTPS, simply add the letter "s" to the URL to switch from HTTP to HTTPS.

```
let response = await fetch('https://localhost:5000/send', {
```

Build the React application for production. I made a production specific folder outside from the dev folder. On package.json, add the build script. This script builds the react application, saves the build to the prod folder and removes it from the dev folder.

2. **Build for Production:** To get your React application ready to be deployed, it needs to undergo a special process called "building for production." This process is like packaging your app in a way that makes it suitable for sharing over the internet. To make things organized, I've created a separate folder specifically for the production version of your app. This makes it super easy when it comes to uploading the production version to GitHub.

Here's how to do it:

- **Creating a Production Folder:** I've set up a special folder outside of your development workspace. This is where the final version of your app that's ready for deployment will be placed.

- **Build Script in package.json:** I've added a special script to the **package.json** file. This script automates the process. First, it builds the React app in the development folder. Then, it copies the built files to the production folder. Finally, it tidies up the development folder by removing the unnecessary build files.

If you're using **create-react-app**, the build script will be:

```
"build": "react-scripts build && XCOPY C:\\Dev\\contactform\\build\\\* C:\\Prod\\contactform_prod /s /y && RMDIR /s /q C:\\Dev\\contactform\\build",
```

If you're using **nano-react-app**, the build script will be:

```
"build": "vite build && XCOPY C:\\Dev\\contactform\\build\\\* C:\\Prod\\contactform_prod /s /y && RMDIR /s /q C:\\Dev\\contactform\\build",
```

3. **Run the Build Script:** Save the changes in your package.json file then run the following command to initiate the production build in your terminal:

```
npm run build
```

4. **Publish to GitHub:** Open the production build folder using VSCode. Go to the source control section and select publish to github as a private repo.
   ![github publish](https://raw.githubusercontent.com/diazelena325/contactform/main/tutorial_images/githubpublish.png)

This will make your production-ready frontend code ready for Cyberpanel.

<a id="Deployment:-GitHub-and-CyberPanel"></a>

## Deployment: GitHub and CyberPanel

<a id="Backend-Deployment"></a>

### Backend Deployment

When it comes to deploying your backend to the server, the process is smooth and straightforward. Here's how you do it:

1. **Remote Connection:** Connect remotely to your CyberPanel server, where your portfolio website is stored. Go to the directory location where your websites public_html is located. Just outside the **public_html** folder, create a folder named **emailsvc**.

The necessary backend files will go inside this folder, which are:

- **config.js**
- **package.json**
- **server.js**

  Remember, there's no need to import the **node_modules** folder; it's already in your **package.json**.

2. **Install Packages:** In the terminal, navigate to the location of your backend files on the server. Install the required packages. You can do this by running either of the following commands:

```
npm install
```

or

```
npm install express nodemailer cors https --save
```

This step ensures that your backend has all the necessary dependencies to run smoothly.

3. **Test Backend:** To ensure that your backend is working correctly on the server, log in to your host service through a terminal, and run the command:

```
npm run mailstart
```

This test run is crucial to confirm that everything is set up and ready for action.

With your backend deployed and successfully tested, you've achieved a significant milestone in bringing your full-stack contact form to life in a live environment.

It's important to note that if you close your terminal that is logged into your host service, the backend could stop running. To ensure continuous operation, follow the upcoming steps that will help you keep your backend running reliably.

<a id="Keeping-the-Backend-Server-Running"></a>

#### Keeping the Backend Server Running: PM2

To ensure the continuous operation of your backend, we'll use a tool called PM2. PM2 allows you to manage various backend services and keep them running efficiently. To get more information about PM2 go to: [https://pm2.keymetrics.io/docs/usage/process-management/](https://pm2.keymetrics.io/docs/usage/process-management/)

1. **Install PM2:** In your terminal, run the following command to install PM2 globally:

```
npm install pm2 -g
```

This command will make PM2 available for managing your backend services.

2. **Unique Start Scripts:** Ensure that each of your backend services has a distinct start script name. For example, in our case, we named our script **mailstart**.

3. **Start the Service:** To initiate a backend service using PM2, execute the following command:

```
pm2 start "npm run mailstart"
```

This command tells PM2 to manage the execution of your backend service.

4. **Stop the Service:** If you need to halt the service, you have two options:

- To stop all backend services simultaneously, run:

```
pm2 stop all
```

- To stop a specific service, provide its unique identifier (ID):

```
pm2 stop <id>
```

By using PM2, you can ensure that your backend services stay active. This is a crucial step in making sure your full-stack contact form remains operational and accessible at all times.

<a id="Frontend-Deployment"></a>

### Frontend Deployment

Deploying the frontend of your application using CyberPanel's Git management feature is the final step towards making your full-stack contact form accessible to users.

1. Log in to your CyberPanel dashboard and navigate to the "Websites" section, then "List Websites" sub-section.

2. Go to the "Manage" section of your website in this list, then look for the "Manage Git" button and click on it.

3. Choose the folder where your portfolio website is deployed in the drop-down list.

4. Look for the "Pull" button and click on it. This action will retrieve the latest changes from your GitHub repository and deploy them to the selected folder.

🥳**Congratulations, your contact form is deployed!** 🏆🎉

<a id="Troubleshooting"></a>

## Troubleshooting

During the process of creating and deploying your full-stack contact form, you might encounter a few issues. Here are a couple of common challenges and their solutions that I came across:

- **Permission Denied Error with SSL Certificate:** If you encounter an EACCES (permission denied) error while using the SSL certificate, it's likely a file permission issue. To resolve this, navigate to the location of the key file (privkey.pem), and change its permissions using the following command:

```
CHMOD 744 privkey.pem
```

- **Auto-Reply Emails Going to Spam:** Sometimes, auto-reply messages can end up in recipients' spam folders. I resolved this by including an HTML version of the message (converted from the text version).

These resources really helped figure it out:

- **[Text to HMTL converter](https://www.textfixer.com/html/convert-text-html.php)** helped with emails ending up in spam folder
- **[This stack overflow](https://stackoverflow.com/questions/40608635/email-send-through-nodemailer-goes-into-spam-for-gmail)** really helped with a nodemailer issue
- **[Test-mailer](https://www.mail-tester.com/)** to see what security issues could appear

<a id="Conclusion"></a>

## Conclusion

🌟You've now gone through the entire process of creating, deploying, and troubleshooting your full-stack contact form!🌟

Let's recap:

- **Tutorial Recap:** You started by creating a sleek and functional frontend contact form using React and then moved on to setting up the backend using Node.js. The form's data is sent via a secure POST request to your backend, and finally an auto-reply message is sent to the user.

- **Error Handling and Security:** Throughout this journey, we've emphasized the importance of handling errors gracefully and prioritizing security. Properly handling errors and ensuring the secure transmission of data are critical aspects of any web application.

- **Experiment and Customize:** While this tutorial provides a solid foundation, don't hesitate to experiment and customize the code to match your specific needs. Every project is unique, and exploring different functionalities can be a great learning experience.

With your full-stack contact form up and running, you're now better equipped to handle communication with visitors to your website or portfolio. As you continue to develop your skills, you'll find even more ways to leverage the power of full-stack development for creating engaging and dynamic web applications.

If you have any questions or if there are additional steps you'd like me to cover, please feel free to let me know.

Happy coding! 🚀🌌🌝

---

If you found this helpful, support my work by sharing this article, referring me for frontend jobs, or if inclined [Buy Me A Coffee](https://www.buymeacoffee.com/elenadiaz32505), [Ko-fi](https://ko-fi.com/elenadiaz), or [Paypal](https://paypal.me/elenadiaz32505). Your support keeps me going – thank you!