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? π€
- Node.js & Express: The dynamic duo for building robust and scalable backend APIs.
- MongoDB: A NoSQL database thatβs flexible, fast, and perfect for handling unstructured data.
- 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
- Initialize your project:
mkdir task-manager
cd task-manager
npm init -y
npm install express mongoose cors dotenv
- 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}`));
- Add a
.env
file:
MONGO_URI=your_mongodb_connection_string
Step 2: Create the Task Model
- 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);
- 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();
});
Step 3: Build the Frontend with Next.js
- Create a new Next.js app:
npx create-next-app@latest task-manager-frontend
cd task-manager-frontend
npm install axios
- 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>
);
}
- 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);
}
Step 4: Connect the Dots π
- Run your backend:
node index.js
- Run your Next.js app:
npm run dev
- 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! π»β¨
Top comments (0)