Search code examples
node.jsreactjsdeploymentnodemailerreact-forms

Changing server.js when deploying


I know almost nothing about NodeJS, but I am building my Portfolio website in React and I wanna include a Contact Form. I use nodemailer but there is something I don't know: I have my server.js file that is listening to port 5000 (app.listen(5000, () => console.log("Server: Running"));). Well, I have this handleSubmit function that is running when the user submits the form:

const handleSubmit = async (e) => {
  e.preventDefault();
  setButtonText("Sending...");
  let response = await fetch("http://localhost:5000/contact", {
    method: "POST",
    headers: { "Content-Type": "Application/json;charset=utf-8" },
    body: JSON.stringify(formDetails),
  });
  setButtonText("Send");
  let result = response.json();
  setFormDetails(formInitialDetails);
  if (result.code === 200)
    setStatus({ succes: true, message: "Message sebt successfully" });
  else setStatus({ succes: false, message: "Something went wrong!" });
}

And the form: <form onSubmit={handleSubmit}>...</form>

Now my question is: If my handleSubmit function is listening at http://localhost:5000/contact what am I supposed to do (to change) in order to make this React App work as I expect when I deploy it. I mean: if I deploy this with GitHub Pages or Netlify the URL will be different than http://localhost:5000/contact, right? So what I have to do before I deploy it?


Solution

  • You can just use environment variable instead of let your url in your code. Like:

    const response = await fetch(process.env.serverUrl, {
        method: "POST",
        headers: { "Content-Type": "Application/json;charset=utf-8" },
        body: JSON.stringify(formDetails),
      });
    

    And then set your environment variable serverUrl in Github Pages (see how here)