I have a React website with a Node.js backend that is deployed to Heroku through my GitHub account. The React website frontend sends contact form requests back to the Node.js backend server, which sends them to an inbox via SMTP. However, while the code works perfectly on localhost, I have had several issues with Heroku deployment. I was able to fix many through code updates, upgrading my dynos, and the like, but this last one is confusing because I think the code is working, but that the node.js server is somehow taking precedence over the React frontend, causing no actual frontend components to display. When I comment out the configuration in the Procfile (web: node server.js
), the frontend code works but at the cost of no backend. I’m not sure where to go from here.
This is my node.js backend code (server.js):
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const cors = require('cors');
const creds = require('./config');
const transporter = nodemailer.createTransport({
host: "smtp.mailtrap.io", // Use the correct Mailtrap SMTP server
port: 2525,
auth: {
user: creds.USER,
pass: creds.PASS
}
});
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/send', (req, res) => {
const { name, email, message } = req.body;
const content = `name: ${name} n email: ${email} n message: ${message}`;
const mail = {
from: email, // Set 'from' as a valid email address
to: '<VALID EMAIL HERE IN MY CODE>', // Change to the email address that you want to receive messages on
subject: 'New Message from Contact Form',
text: content
};
transporter.sendMail(mail, (err, data) => {
if (err) {
console.log(err); // Log the error for debugging
res.status(500).json({
status: 'fail',
error: err.message
});
} else {
res.status(200).json({
status: 'success'
});
}
});
});
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', router);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This is my frontend Contact.js code:
import React from 'react';
import "../App.css";
import "./Contact.css";
import FormData from 'form-data';
function Contact() {
function handleSubmit(event) {
event.preventDefault();
const form = event.target;
const formInfo = new FormData(form);
const jsonBody = Object.fromEntries(formInfo.entries()); // Ensure correct conversion
console.log(jsonBody);
async function fetchData() {
try {
// Determine the base URL dynamically based on environment
const baseURL = `${window.location.protocol}//${window.location.hostname}:3002`;
const response = await fetch(`${baseURL}/send`, {
method: "POST",
body: JSON.stringify(jsonBody),
headers: {
"Content-Type": "application/json"
}
});
const result = await response.json();
if (result.status === "success") {
alert("Message sent!");
} else {
alert("Message failed to send.");
}
} catch (error) {
console.error('Error:', error);
alert("Message failed to send due to an error.");
}
}
fetchData();
}
return (
<>
<div className="container">
<style>{'body { background-color: black; }'}</style>
<form method="post" onSubmit={handleSubmit}>
<label>Name: <input type="text" className = "textbox" name="name"></input></label>
<label>Email: <input type="email" className = "textbox" name="email"></input></label>
<div className="input-help">
<label> Message:
<textarea type="text" className = "textbox" name="message" placeholder="Thank you for messaging!" columns="200" rows="10" />
</label>
</div>
<button className = "submit-button" type="submit">Submit</button>
</form>
</div>
</>
);
}
export default Contact;
This is the server message that displays when node server.js is run in the terminal:
Server running on port 3002
Server is ready to take messages
This is the visual code on localhost:3000:
The messages are sent to my test inbox once Submit is clicked from localhost.
I know that this has something to do with the app.get and res.send code from server.js, but the code as a whole doesn’t run on Heroku at all without it.
Here is the app deployed to Heroku with no commented-out Procfile:
Otherwise, it looks the same as localhost, but sends no emails (although it does register the JSON object in the console).
Here are the Heroku logs for the web process:
2024-05-22T16:30:51.008189+00:00 heroku[web.1]: Starting process with command `node server.js`
2024-05-22T16:30:52.247939+00:00 app[web.1]: Server running on port 16613
2024-05-22T16:30:52.353130+00:00 app[web.1]: Server is ready to take messages
2024-05-22T16:30:52.773075+00:00 heroku[web.1]: State changed from starting to up
Here are the Heroku logs for the overall website:
2024-05-22T16:30:51.008189+00:00 heroku[web.1]: Starting process with command `node server.js`
2024-05-22T16:30:52.247939+00:00 app[web.1]: Server running on port 16613
2024-05-22T16:30:52.353130+00:00 app[web.1]: Server is ready to take messages
2024-05-22T16:30:52.773075+00:00 heroku[web.1]: State changed from starting to up
2024-05-22T16:33:47.166236+00:00 heroku[router]: at=info method=GET path="/" host=<website_name>.herokuapp.com request_id=<here> fwd="<numbers>" dyno=web.1 connect=0ms service=6ms status=200 bytes=244 protocol=https
2024-05-22T16:33:47.313441+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=<website_name>.herokuapp.com request_id=<here> fwd="<here>" dyno=web.1 connect=0ms service=4ms status=404 bytes=426 protocol=https
2024-05-22T16:48:06.188583+00:00 heroku[router]: at=info method=GET path="/" host=<website_name>.herokuapp.com request_id=<texthere> fwd="<numbers>" dyno=web.1 connect=0ms service=1ms status=304 bytes=181 protocol=https