Home Education How to Create a Full Stack App Using Next.js and MongoDB Atlas

How to Create a Full Stack App Using Next.js and MongoDB Atlas

91
0

Building full stack applications has become much easier with modern tools and frameworks. One powerful combination that many developers use today is Next.js for the frontend and MongoDB Atlas for the backend database. This pair makes it easy to create fast, secure, and scalable web apps that work well for all kinds of users.

In this blog, we will walk through the steps to build a full stack app using Next.js and MongoDB Atlas. You’ll learn how these tools work together and how you can build something useful from scratch. This guide is beginner-friendly, so if you are new to full stack development, don’t worry — we’ll keep everything simple and clear.

If you’re planning to start a career in web development, joining a full stack developer course can give you a solid foundation. It can also help you become comfortable with tools like Next.js, MongoDB, and others used in real-world projects.

What is Next.js?

Next.js is a popular React framework. It helps you build server-side rendered (SSR) and static websites using React. It’s fast, supports SEO, and has features like routing, API routes, and image optimization built-in.

Benefits of Next.js:

  • Easy to use with React
  • Server-side rendering support
  • Automatic code splitting
  • Built-in routing and API support
  • Works well with TypeScript

What is MongoDB Atlas?

It is the cloud version of MongoDB. Instead of setting up MongoDB on your local machine or server, you can use MongoDB Atlas to create and manage databases online. It is secure, scalable, and easy to connect with modern web apps.

Benefits of MongoDB Atlas:

  • Cloud-based, no installation required
  • Easy to scale
  • Built-in security features
  • Simple interface for database management

Step-by-Step Guide to Build the App

Let’s now build a simple full stack app using Next.js and MongoDB Atlas. This app will allow users to submit messages, and those messages will be stored in a database.

Step 1: Set Up Your Project

First, create a new Next.js app. You can use this command in your terminal:

npx create-next-app@latest my-fullstack-app

After the project is created, move into the project folder:

cd my-fullstack-app

Start the development server:

npm run dev

Look at your app running at http://localhost:3000.

Step 2: Set Up MongoDB Atlas

Go to the MongoDB Atlas website and sign up for a free account. Once you’re logged in:

  • Create a new cluster (free tier is enough)
  • Create a database and collection (for example, database: messagesDB, collection: messages)
  • Include your IP address to the access list so you can connect
  • Create a database user and password
  • Copy the connection string (you’ll need it in the next step)

Step 3: Connect MongoDB Atlas to Next.js

Install the MongoDB Node.js driver:

npm install mongodb

Create a new file lib/mongodb.js in your project. Add the following code:

import { MongoClient } from ‘mongodb’;

const uri = process.env.MONGODB_URI;

const options = {};

let client;

let clientPromise;

if (!process.env.MONGODB_URI) {

  throw new Error(‘Please add your MongoDB URI to .env.local’);

}

if (!clientPromise) {

  client = new MongoClient(uri, options);

  clientPromise = client.connect();

}

export default clientPromise;

Now, create a .env.local file in the root folder of your project:

MONGODB_URI=your_connection_string_here

Replace your_connection_string_here with your actual MongoDB URI.

Step 4: Create the API Route

In Next.js, you can create backend APIs in the pages/api folder. Let’s create an API to save messages.

Create a new file: pages/api/messages.js

import clientPromise from ‘../../lib/mongodb’;

export default async function handler(req, res) {

  if (req.method === ‘POST’) {

    const { name, message } = req.body;

    if (!name || !message) {

      return res.status(400).json({ error: ‘Missing name or message’ });

    }

    try {

      const client = await clientPromise;

      const db = client.db(‘messagesDB’);

      const result = await db.collection(‘messages’).insertOne({ name, message });

      res.status(200).json({ success: true, id: result.insertedId });

    } catch (error) {

      res.status(500).json({ error: ‘Database error’ });

    }

  } else {

    res.status(405).json({ error: ‘Method not allowed’ });

  }

}

This API accepts POST requests and saves the data to your MongoDB Atlas database.

Step 5: Create the Form on the Frontend

Open pages/index.js and add a form to collect name and message.

import { useState } from ‘react’;

export default function Home() {

  const [name, setName] = useState(”);

  const [message, setMessage] = useState(”);

  const [response, setResponse] = useState(”);

  async function handleSubmit(e) {

    e.preventDefault();

    const res = await fetch(‘/api/messages’, {

      method: ‘POST’,

      headers: { ‘Content-Type’: ‘application/json’ },

      body: JSON.stringify({ name, message }),

    });

    const data = await res.json();

    if (data.success) {

      setResponse(‘Message sent!’);

      setName(”);

      setMessage(”);

    } else {

      setResponse(‘Error sending message.’);

    }

  }

  return (

    <div>

      <h1>Send a Message</h1>

      <form onSubmit={handleSubmit}>

        <input type=”text” value={name} onChange={(e) => setName(e.target.value)} placeholder=”Your Name” required />

        <textarea value={message} onChange={(e) => setMessage(e.target.value)} placeholder=”Your Message” required />

        <button type=”submit”>Send</button>

      </form>

      <p>{response}</p>

    </div>

  );

}

Now, when users fill out the form and click “Send”, their data is stored in MongoDB Atlas.

Step 6: Read Messages (Optional)

You can create another API route to fetch messages and show them on the page. Create pages/api/get-messages.js:

import clientPromise from ‘../../lib/mongodb’;

export default async function handler(req, res) {

  try {

    const client = await clientPromise;

    const db = client.db(‘messagesDB’);

    const messages = await db.collection(‘messages’).find({}).toArray();

    res.status(200).json({ messages });

  } catch (error) {

    res.status(500).json({ error: ‘Database error’ });

  }

}

Then, fetch and display these messages on the frontend.

Deployment

When you are ready to go live, you can deploy your app easily using platforms like Vercel (the creators of Next.js). Just make sure to add your environment variables to the deployment platform.

Many students who take full stack developer classes learn how to deploy full stack apps, manage environment variables, and use cloud databases like MongoDB Atlas in real projects. This real-world practice helps them become job-ready.

Final Thoughts

Building full stack applications with Next.js and MongoDB Atlas is a great way to learn modern web development. These tools are powerful, flexible, and widely used in the industry. By learning how to use them together, you can create dynamic web apps with both frontend and backend features.

From setting up the project to writing API routes and connecting to the database, every step you took in this guide brings you closer to becoming a confident full stack developer. If you want to keep learning and growing, a full stack developer course in hyderabad can guide you through more advanced topics, projects, and interview skills.

As you keep practicing, you’ll be able to build more complex apps like dashboards, e-commerce stores, chat apps, and more — all using the same basic tools you just learned.

Contact Us:

Name: ExcelR – Full Stack Developer Course in Hyderabad

Address: Unispace Building, 4th-floor Plot No.47 48,49, 2, Street Number 1, Patrika Nagar, Madhapur, Hyderabad, Telangana 500081

Phone: 087924 83183

LEAVE A REPLY

Please enter your comment!
Please enter your name here