Written by: Geoffrey Callaghan

How To Create A Contact Form With Render

How To Create A Contact Form With Render

Creating a contact form with Render involves a few steps: setting up the HTML form, creating an API endpoint to handle the form submissions, and deploying your project to Render. Here’s a step-by-step guide to help you get started:

1. Set Up the HTML Form

Create an HTML file for your contact form. Here’s a basic example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form id="contact-form">
        <p>
            <label>Name: <input type="text" name="name" required></label>
        </p>
        <p>
            <label>Email: <input type="email" name="email" required></label>
        </p>
        <p>
            <label>Message: <textarea name="message" required></textarea></label>
        </p>
        <p>
            <button type="submit">Send</button>
        </p>
    </form>
    <div id="form-response"></div>
</body>
<script>
document.getElementById('contact-form').addEventListener('submit', async function(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);
    const responseElement = document.getElementById('form-response');

    try {
        const response = await fetch('/api/contact', {
            method: 'POST',
            body: JSON.stringify(Object.fromEntries(formData)),
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            responseElement.textContent = 'Form successfully submitted';
            form.reset();
        } else {
            responseElement.textContent = 'Error submitting form';
        }
    } catch (error) {
        responseElement.textContent = 'Error submitting form';
    }
});
</script>
</html>

2. Create an API Endpoint for Form Handling

Next, create an API endpoint to handle the form submissions. In a Render project, you typically place this in a server file.

Directory structure:

project-root/
├── public/
│   └── index.html
├── src/
│   └── api.js
├── package.json
└── render.yaml

src/api.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.json());

app.post('/api/contact', (req, res) => {
    const { name, email, message } = req.body;

    // Process the form data here (e.g., save it to a database, send an email, etc.)
    console.log('Form data received:', { name, email, message });

    res.status(200).json({ message: 'Form submission received' });
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

3. Create package.json

Add a package.json file to manage your dependencies and scripts:

{
  "name": "contact-form",
  "version": "1.0.0",
  "main": "src/api.js",
  "scripts": {
    "start": "node src/api.js"
  },
  "dependencies": {
    "express": "^4.17.1",
    "body-parser": "^1.19.0"
  }
}

4. Create render.yaml

Create a render.yaml file to configure your Render service:

services:
  - type: web
    name: contact-form
    env: node
    plan: free
    buildCommand: 'npm install'
    startCommand: 'npm start'
    envVars:
      - key: NODE_ENV
        value: production
    staticPublishPath: public

5. Deploy to Render

  1. Push your project to GitHub, GitLab, or Bitbucket: Ensure your project is part of a repository on one of these platforms.

  2. Connect your repository to Render:

    • Go to Render.
    • Log in or sign up if you haven’t already.
    • Click on “New Web Service” and import your repository.
    • Follow the prompts to configure and deploy your service.

6. Test Your Form

After deploying your site, navigate to the URL provided by Render and test your form by submitting a message. Check the logs in the Render dashboard to verify that submissions are being processed correctly.

7. Optional: Customize Your Form

  • Styling: Add CSS to style your form. You can include styles directly in the HTML file or link to an external stylesheet.
  • JavaScript: Enhance the form’s functionality with additional JavaScript, such as more advanced form validation or UI improvements.

By following these steps, you’ll have a fully functional contact form deployed on Render, capable of handling submissions effectively.