DEV Community

Cover image for πŸš€ Build a Full-Stack App with Node.js, Express, MongoDB, and Next.js: The Ultimate Guide! πŸš€
Raj Aryan
Raj Aryan

Posted on

πŸš€ Build a Full-Stack App with Node.js, Express, MongoDB, and Next.js: The Ultimate Guide! πŸš€

Hey Dev Community! πŸ‘‹

Are you ready to level up your full-stack development game? Let’s dive into building a blazing-fast, modern web app using Node.js, Express, MongoDB, and Next.js! Whether you're a beginner or a seasoned developer, this stack is a game-changer for building scalable, performant, and SEO-friendly applications. 🌟


Why This Stack? πŸ€”

  1. Node.js & Express: The dynamic duo for building robust and scalable backend APIs.
  2. MongoDB: A NoSQL database that’s flexible, fast, and perfect for handling unstructured data.
  3. Next.js: The React framework that gives you server-side rendering, static site generation, and API routes out of the box. πŸš€

What We’re Building πŸ› οΈ

A Task Manager App where users can:

  • Create, read, update, and delete tasks (CRUD operations).
  • View tasks in a clean, responsive UI.
  • Enjoy lightning-fast performance thanks to Next.js.

Step 1: Set Up Your Backend with Node.js & Express

  1. Initialize your project:
   mkdir task-manager
   cd task-manager
   npm init -y
   npm install express mongoose cors dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Create an index.js file:
   const express = require('express');
   const mongoose = require('mongoose');
   const cors = require('cors');
   require('dotenv').config();

   const app = express();
   const PORT = process.env.PORT || 5000;

   // Middleware
   app.use(cors());
   app.use(express.json());

   // MongoDB Connection
   mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
     .then(() => console.log('MongoDB Connected!'))
     .catch(err => console.log(err));

   // Routes
   app.get('/', (req, res) => {
     res.send('Task Manager API is running!');
   });

   app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode
  1. Add a .env file:
   MONGO_URI=your_mongodb_connection_string
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Task Model

  1. Create a models/Task.js file:
   const mongoose = require('mongoose');

   const TaskSchema = new mongoose.Schema({
     title: { type: String, required: true },
     description: { type: String, required: true },
     completed: { type: Boolean, default: false },
   }, { timestamps: true });

   module.exports = mongoose.model('Task', TaskSchema);
Enter fullscreen mode Exit fullscreen mode
  1. Add CRUD routes in index.js:
   const Task = require('./models/Task');

   // Create a task
   app.post('/tasks', async (req, res) => {
     const task = new Task(req.body);
     await task.save();
     res.status(201).send(task);
   });

   // Get all tasks
   app.get('/tasks', async (req, res) => {
     const tasks = await Task.find();
     res.send(tasks);
   });

   // Update a task
   app.put('/tasks/:id', async (req, res) => {
     const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
     res.send(task);
   });

   // Delete a task
   app.delete('/tasks/:id', async (req, res) => {
     await Task.findByIdAndDelete(req.params.id);
     res.status(204).send();
   });
Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Frontend with Next.js

  1. Create a new Next.js app:
   npx create-next-app@latest task-manager-frontend
   cd task-manager-frontend
   npm install axios
Enter fullscreen mode Exit fullscreen mode
  1. Create a pages/index.js file:
   import { useEffect, useState } from 'react';
   import axios from 'axios';

   export default function Home() {
     const [tasks, setTasks] = useState([]);

     useEffect(() => {
       fetchTasks();
     }, []);

     const fetchTasks = async () => {
       const res = await axios.get('/api/tasks');
       setTasks(res.data);
     };

     return (
       <div>
         <h1>Task Manager</h1>
         <ul>
           {tasks.map(task => (
             <li key={task._id}>{task.title}</li>
           ))}
         </ul>
       </div>
     );
   }
Enter fullscreen mode Exit fullscreen mode
  1. Add an API route in pages/api/tasks.js:
   import axios from 'axios';

   export default async function handler(req, res) {
     const { data } = await axios.get('http://localhost:5000/tasks');
     res.status(200).json(data);
   }
Enter fullscreen mode Exit fullscreen mode

Step 4: Connect the Dots πŸ”—

  1. Run your backend:
   node index.js
Enter fullscreen mode Exit fullscreen mode
  1. Run your Next.js app:
   npm run dev
Enter fullscreen mode Exit fullscreen mode
  1. Visit http://localhost:3000 and see your Task Manager in action! πŸŽ‰

Why This Stack Rocks πŸš€

  • Scalability: Node.js and MongoDB handle large-scale applications with ease.
  • Performance: Next.js ensures your app is fast and SEO-friendly.
  • Developer Experience: Modern tools and frameworks make development a breeze.

Your Turn! πŸ› οΈ

Clone the repo, tweak the code, and make it your own! Add features like user authentication, due dates, or even drag-and-drop functionality. The possibilities are endless! 🌈


πŸ’¬ Let’s Discuss!

What’s your favorite stack for building full-stack apps? Have you tried this combo before? Share your thoughts and tips in the comments below! πŸ‘‡

Happy Coding! πŸ’»βœ¨

NodeJS #Express #MongoDB #NextJS #FullStack #WebDev #JavaScript

Top comments (0)