Sign Up Form with MERN Stack – Registration Form with MongoDB, Express JS, React JS, and Node JS

Posted by

In this tutorial, we will learn how to create a registration form using the MERN stack, which consists of MongoDB, Express JS, React JS, and Node JS. We will start by creating a simple sign-up form in HTML and then move on to setting up the backend with Node JS and Express, and finally, we will store the user data in MongoDB.

Step 1: Create a simple sign-up form in HTML
Let’s start by creating a simple sign-up form using HTML. Create a new file called index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
  <title>Sign Up Form</title>
</head>
<body>
  <form>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br><br>

    <button type="submit">Sign Up</button>
  </form>
</body>
</html>

This will create a simple sign-up form with three fields: Name, Email, and Password. When the form is submitted, it will send a POST request to the backend.

Step 2: Setting up the backend with Node JS and Express
Now, let’s create a backend server using Node JS and Express. Create a new folder called server and inside that folder, create a new file called server.js. Add the following code to set up the server:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 5000;

app.use(bodyParser.json());

app.post('/signup', (req, res) => {
  const {name, email, password} = req.body;
  // Save the user data to MongoDB here
  res.json({message: 'User signed up successfully'});
});

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

This code sets up an Express server that listens on port 5000. It also defines a POST route /signup, which will handle the sign-up form submission.

Step 3: Storing user data in MongoDB
To store user data in MongoDB, we need to set up a connection to the database. Install the mongoose package by running the following command:

npm install mongoose

Next, add the following code to connect to MongoDB and save the user data:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp');

const User = mongoose.model('User', {
  name: String,
  email: String,
  password: String
});

app.post('/signup', (req, res) => {
  const {name, email, password} = req.body;
  const user = new User({name, email, password});
  user.save()
    .then(() => {
      res.json({message: 'User signed up successfully'});
    })
    .catch((err) => {
      res.status(500).json({error: err.message});
    });
});

Now, when a user signs up using the form, their data will be saved in the MongoDB database.

Step 4: Connecting the frontend with the backend
To connect the frontend with the backend, we need to send a POST request with the form data. Add the following code to the index.html file:

<script>
  document.querySelector('form').addEventListener('submit', async (e) => {
    e.preventDefault();

    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    const response = await fetch('http://localhost:5000/signup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({name, email, password})
    });

    const data = await response.json();
    alert(data.message);
  });
</script>

This code listens for the form submission event, collects the form data, and sends a POST request to the backend server. It then displays a message confirming that the user has signed up successfully.

That’s it! You have now created a registration form using the MERN stack. Users can sign up using the form, and their data will be stored in MongoDB. Feel free to customize the form and the backend logic to fit your requirements.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@rickyvarquez5955
2 months ago

Can you share the source code here