DEV Community

Cover image for How to connect MongoDB to your Next.js application
Adam
Adam

Posted on

How to connect MongoDB to your Next.js application

Image description

Ready to create your first database-connected sign-up form? It's easier than you think! In this tutorial, I'll walk you through the process step-by-step, so you can get started right away.

Step 0 : Create your mongodb account if you havent yet, you can connect through your gmail or github account, otherwise, create a new account and you will be directed to the dashboard. 
Enter fullscreen mode Exit fullscreen mode

Image description

- Click on the +New Project button
Enter fullscreen mode Exit fullscreen mode

Image description

- Name your project
Enter fullscreen mode Exit fullscreen mode

Image description

- Click on create project
Enter fullscreen mode Exit fullscreen mode

Image description

- Then you will be taken to this overview page, click on the +create button
Enter fullscreen mode Exit fullscreen mode

Image description

- Choose the M0, the free version, then click create.
- Now you will be directed to a security quickstart page.
Enter fullscreen mode Exit fullscreen mode

Image description

- choose your own username, and autogenerate a secure password to add to your password file and make sure to add to your .gitignore file to keep it safe. Or if you would like to create your own password, feel free to do so. Then click on Create user.
Enter fullscreen mode Exit fullscreen mode

Image description

- in section 2, choose My Local Environment, and add your current IP address, if ones been created for you already, move on and click Finish and Close at the bottom of the page.
Enter fullscreen mode Exit fullscreen mode

Image description

- now, you will be redirected to the overview page, click on the dark green connect button in the database deployments cluster0 tab.
Enter fullscreen mode Exit fullscreen mode

Image description

- click on Drivers
Enter fullscreen mode Exit fullscreen mode

Image description

- follow the steps, by opening your terminal and installing mongodb :
Enter fullscreen mode Exit fullscreen mode
    npm install mongodb 
Enter fullscreen mode Exit fullscreen mode
- then copy your **connection string** and paste somewhere for later use.

1. Create your sign up page, this is where you create the form variables such as name, subject and message. Here is mine :
Enter fullscreen mode Exit fullscreen mode
    import config from "@config/config.json";
    import Banner from "./components/Banner";
    import ImageFallback from "./components/ImageFallback";
    import React, { useState } from 'react';
    import { LoginLink } from "@kinde-oss/kinde-auth-nextjs/server";
    import { RegisterLink } from "@kinde-oss/kinde-auth-nextjs/server";
    import { useRouter } from 'next/router';

    const Signup = ({ data }) => {


          const { frontmatter } = data;
          const { title } = frontmatter;


          const [formData, setFormData] = useState({
            name: '',
            subject: '',
            message: '',
          });

          const handleChange = (e) => {
            const { name, value } = e.target;
            setFormData({ ...formData, [name]: value });
          };

          const router = useRouter(); // Initialize the router

          const handleSubmit = async (e) => {
            e.preventDefault();

            // Assuming you have a backend API endpoint for saving user data
            const apiUrl = '/api/signup'; // Replace with your actual API endpoint

            try {
              const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
              });

              if (response.ok) {
                // Data was successfully sent to the server
                alert('Sign Up Successful');
                // Optionally, you can reset the form here
                setFormData({
                  name: '',
                  subject: '',
                  message: '',
                });
                // Redirect the user to a different page after a successful sign-up
                router.push('/about'); // Replace '/success' with the actual path you want to redirect to
              } else {
                // Handle errors
                alert('Sign Up failed, but you are getting there. Keep thinking, trying, learning');
              }
            } catch (error) {
              console.error('Error:', error);
              alert('An error occurred while signing up');
            }
          };


      return (
        <section className="section">
          <Banner title={title} />

          <div className="container">
            <div className="section row items-center justify-center">
              <div className="animate lg:col-5">
                <ImageFallback
                  className="mx-auto lg:pr-10"
                  src="/images/vectors/contact.png"
                  width={497}
                  height={397}
                  alt=""
                />
              </div>
            <div className="animate lg:col-5">
                <form
                    onSubmit={handleSubmit}
                    className="contact-form rounded-xl p-6 shadow-[0_4px_25px_rgba(0,0,0,0.05)]"
                >
                    <h2 className="h4 mb-6">Sign Up</h2>
                    <div className="mb-6">
                    <label className="mb-2 block font-medium text-dark" htmlFor="name">
                        Name
                    </label>
                    <input
                        className="form-input w-full"
                        name="name"
                        placeholder="Full Name"
                        type="text"
                        required
                        value={formData.name}
                        onChange={handleChange}
                    />
                    </div>

                    <div className="mb-6">
                    <label className="mb-2 block font-medium text-dark" htmlFor="name">
                        Username
                    </label>
                    <input
                        className="form-input w-full"
                        name="username"
                        placeholder="Username"
                        type="text"
                        required
                        value={formData.name}
                        onChange={handleChange}
                    />
                    </div>

                    <div className="mb-6">
                    <label className="mb-2 block font-medium text-dark" htmlFor="name">
                        Password
                    </label>
                    <input
                        className="form-input w-full"
                        name="password"
                        placeholder="password"
                        type="text"
                        required
                        value={formData.name}
                        onChange={handleChange}
                    />
                    </div>

                    <div className="mb-6">
                    <label className="mb-2 block font-medium text-dark" htmlFor="name">
                        Re-enter password
                    </label>
                    <input
                        className="form-input w-full"
                        name="re_enter_password"
                        placeholder="Re-enter password"
                        type="text"
                        required
                        value={formData.name}
                        onChange={handleChange}
                    />
                    </div>
                    <button type="submit">Sign Up</button>
                </form>
            </div>
            </div>
          </div>
        </section>
      );
    };

    export default Signup;
Enter fullscreen mode Exit fullscreen mode
  • it might seem long, but the most important aspects of the code that you need to have here is the router, and the handle submit methods, then declaring the onSubmit={handleSubmit} function in the section.
//important key parts you need to have : 

import { useRouter } from 'next/router';

// ... 

const handleChange = (e) => {
    const {name, value} = e.target;
    setFormData({...formData, [name] : value);
};

const router = useRouter(); // initialize the router 

const handleSubmit = async (e) {
    e.preventDefault();

    // declare the backend api endpoint for saving the user's data 
    const apiUrl = '/api/signup'; //replace with your actual path 

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData), 
        });

    if(response.ok) {
        // Alert if the data was successfully send to the user 
        alert('Sign up Successful');

        // This is an option, you can reset the form 
        setFormData({
            name: '';
            subject: '';
            message: '';
        });

        // Redirect the user to the login page after successfully signing up. 
        router.push('/login'); // replace with the path to your login page 
    } else { 
        //handle error 
        alert("Sign up failed, but you are getting there, dont give up, keep trying, learning and growing");
        console.error("Error: ", error);
        alert("An error occured while signing up");
    }
};

//.... 

<form
    onSubmit={handleSubmit}
    <label>Name</label>
    <input
        name="name" 
        placeholder="full name"
        type="text"
        required
        value={formData.name}
        onChange={handleChange}
    />
    <label>Username</label>
    <input
        name="username" 
        placeholder="Username"
        type="text"
        required
        value={formData.name}
        onChange={handleChange}
    />
    <label>Password</label>
    <input
        name="password" 
        placeholder="password"
        type="text"
        required
        value={formData.name}
        onChange={handleChange}
    />
    <label>Re-Enter password</label>
    <input
        name="re_enter_password" 
        placeholder="Re-Enter password"
        type="text"
        required
        value={formData.name}
        onChange={handleChange}
    />
</form>

Enter fullscreen mode Exit fullscreen mode
  1. Then create a mongodb.js file in the same folder as your Signup.js file.
import { MongoClient } from 'mongodb';

const uri = "mongodb+srv://aedamjung:l4p7Wd4daeh3S1hb@cluster1.pvc5ijl.mongodb.net/?retryWrites=true&w=majority"; // Replace with your MongoDB URI

export async function connectToDatabase() {
  const client = new MongoClient(uri, { useNewUrlParser: true });

  try {
    await client.connect();
        const db = client.db("verify_user_database"); // Specify your database name if necessary    return { client, db };
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Now here is where you use that connection string, so paste the connection string you copied earlier and replace the with the password you created earlier.
  • Now we are going to create the database to store the user’s sign up details.
  • Go back to mongodb, and click on database

Image description

Image description

  • now click on the browse collections, located in the middle of the screen.

Image description

  • Click on Add My Own Data

Image description

  • Enter your database, and enter the collection name users, then create.
  1. Then, create a signup.js file to connect the database collection name users to the code.
// pages/api/signup.js

import { connectToDatabase } from '../../lib/utils/mongodb';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, subject, message } = req.body;

    // Validation (you can customize this to suit your requirements)
    if (!name || !subject || !message) {
      return res.status(400).json({ error: 'All fields are required.' });
    }

    try {
      const { client, db } = await connectToDatabase();

      // Insert user data into the database
            // The user's data is automatically inserted into the Collection Name user in the verify_user_database database 
      await db.collection('users').insertOne({ name, subject, message });

      // Close the MongoDB connection
      client.close();

      return res.status(201).json({ message: 'User created successfully.' });
    } catch (error) {
      console.error('Error inserting user:', error);
      console.error("Error details: ", error);
      return res.status(500).json({ error: 'Internal server error.' });
    }
  } else {
    res.status(405
).end(); // Method Not Allowed
  }
}
Enter fullscreen mode Exit fullscreen mode

Congratulations on creating your first database-connected sign-up form! I know it can be tricky to figure out how to connect the database at first, but I'm glad you persevered.

Here are a few tips for improving your sign-up form:

  • Validate the user input. This will help to prevent users from entering invalid data, such as empty fields or invalid email addresses.

  • Hash the user's password. This will help to protect the user's password from being compromised in the event of a data breach.

  • Send the user a confirmation email. This will help to ensure that the user's email address is valid and that they actually want to create an account.

Once you've implemented these tips, you'll have a secure and reliable sign-up form that you can use for your website or application.

I hope this helps!

Image description

Top comments (0)