DEV Community

Cover image for Part 3 - Building a Full Stack Contact Form: Deployment 2023
Elena Diaz
Elena Diaz

Posted on • Edited on

Part 3 - Building a Full Stack Contact Form: Deployment 2023

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

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.

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/

  1. Install HTTPS Package: Start by installing the https package using the following command in your terminal:
npm i https
Enter fullscreen mode Exit fullscreen mode
  1. Import HTTPS Module: At the top of your server.js file, import the https module as follows:
const https = require('https');
Enter fullscreen mode Exit fullscreen mode
  1. 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}`)
);
Enter fullscreen mode Exit fullscreen mode

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.

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', {
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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",
Enter fullscreen mode Exit fullscreen mode

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",
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. 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

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

Deployment: GitHub and CyberPanel

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.

  1. 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
Enter fullscreen mode Exit fullscreen mode

or

npm install express nodemailer cors https --save
Enter fullscreen mode Exit fullscreen mode

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

  1. 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
Enter fullscreen mode Exit fullscreen mode

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.

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/

  1. Install PM2: In your terminal, run the following command to install PM2 globally:
npm install pm2 -g
Enter fullscreen mode Exit fullscreen mode

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

  1. 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.

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

pm2 start "npm run mailstart"
Enter fullscreen mode Exit fullscreen mode

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

  1. Stop the Service: If you need to halt the service, you have two options:
  • To stop all backend services simultaneously, run:
pm2 stop all
Enter fullscreen mode Exit fullscreen mode
  • To stop a specific service, provide its unique identifier (ID):
pm2 stop <id>
Enter fullscreen mode Exit fullscreen mode

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.

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! ๐Ÿ†๐ŸŽ‰

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
Enter fullscreen mode Exit fullscreen mode
  • 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:

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, Ko-fi, or Paypal. Your support keeps me going โ€“ thank you!

Top comments (0)