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/
- Install HTTPS Package: Start by installing the https package using the following command in your terminal:
npm i https
- Import HTTPS Module: At the top of your server.js file, import the https module as follows:
const https = require('https');
- 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.
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:
- 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.
- 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",
- 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
- 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.
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:
- 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.
- 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.
- 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.
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/
- 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.
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.
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.
- 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.
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.
Log in to your CyberPanel dashboard and navigate to the "Websites" section, then "List Websites" sub-section.
Go to the "Manage" section of your website in this list, then look for the "Manage Git" button and click on it.
Choose the folder where your portfolio website is deployed in the drop-down list.
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
- 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 helped with emails ending up in spam folder
- This stack overflow really helped with a nodemailer issue
- Test-mailer to see what security issues could appear
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)