🕵️ SicherheitslückenWhat continuous operational resilience looks like under DORA(09.09.2026 um 17:53 Uhr)
🔧 AI Nachrichten OpenAI seeks tougher AI rules. CIOs may feel the ripple effects(10.09.2026 um 12:11 Uhr)
🔧 AI Nachrichten Mistral valued at €21bn after €3bn Series D funding round(08.09.2026 um 10:19 Uhr)
🪟 Windows TippsWindows XP's Cursor Indicator Is Getting a Windows 11 Refresh(25.08.2026 um 13:00 Uhr)
🕵️ SicherheitslückenWhat continuous operational resilience looks like under DORA(09.09.2026 um 17:53 Uhr)
🔧 AI Nachrichten OpenAI seeks tougher AI rules. CIOs may feel the ripple effects(10.09.2026 um 12:11 Uhr)
🔧 AI Nachrichten Mistral valued at €21bn after €3bn Series D funding round(08.09.2026 um 10:19 Uhr)
🪟 Windows TippsWindows XP's Cursor Indicator Is Getting a Windows 11 Refresh(25.08.2026 um 13:00 Uhr)

🔧 Programmierung 🕛 vor 2 Jahren 4 Min Lesezeit
0

Next JS Blog App

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

To build a blog app using Next.js with both backend and frontend, where users can add and delete blogs, and store the data in a database, follow these steps:






1. Set Up Next.js Project



First, create a new Next.js project if you haven't already:




CODE
npx create-next-app@latest blog-app
cd blog-app
npm install









2. Set Up Database



For this project, let's use MongoDB via Mongoose as the database.




  • Install Mongoose:




CODE
npm install mongoose







  • Create a MongoDB database using services like MongoDB Atlas or use a local MongoDB setup.


  • Connect to MongoDB by creating a lib/mongodb.js file:





CODE
// lib/mongodb.js
import mongoose from 'mongoose';

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
throw new Error('Please define the MONGODB_URI environment variable');
}

let cached = global.mongoose;

if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}

async function dbConnect() {
if (cached.conn) {
return cached.conn;
}

if (!cached.promise) {
cached.promise = mongoose.connect(MONGODB_URI).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}

export default dbConnect;






Add the MONGODB_URI to your .env.local file:




CODE
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/blog-app?retryWrites=true&w=majority









3. Define Blog Schema



Create a model for blogs in models/Blog.js:




CODE
// models/Blog.js
import mongoose from 'mongoose';

const BlogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
}, { timestamps: true });

export default mongoose.models.Blog || mongoose.model('Blog', BlogSchema);









4. Create API Routes for Blog



In Next.js, you can create API routes in the pages/api directory.




  • Create pages/api/blog/index.js for handling GET and POST requests (adding blogs):




CODE
// pages/api/blog/index.js
import dbConnect from '../../../lib/mongodb';
import Blog from '../../../models/Blog';

export default async function handler(req, res) {
const { method } = req;

await dbConnect();

switch (method) {
case 'GET':
try {
const blogs = await Blog.find({});
res.status(200).json({ success: true, data: blogs });
} catch (error) {
res.status(400).json({ success: false });
}
break;
case 'POST':
try {
const blog = await Blog.create(req.body);
res.status(201).json({ success: true, data: blog });
} catch (error) {
res.status(400).json({ success: false });
}
break;
default:
res.status(400).json({ success: false });
break;
}
}







  • Create pages/api/blog/[id].js for handling DELETE requests:




CODE
// pages/api/blog/[id].js
import dbConnect from '../../../lib/mongodb';
import Blog from '../../../models/Blog';

export default async function handler(req, res) {
const { method } = req;
const { id } = req.query;

await dbConnect();

switch (method) {
case 'DELETE':
try {
const blog = await Blog.findByIdAndDelete(id);
if (!blog) {
return res.status(400).json({ success: false });
}
res.status(200).json({ success: true, data: {} });
} catch (error) {
res.status(400).json({ success: false });
}
break;
default:
res.status(400).json({ success: false });
break;
}
}









5. Create Frontend for Adding and Displaying Blogs




  • Create a page pages/index.js for listing all blogs and a form for adding new blogs:




CODE
// pages/index.js
import { useState, useEffect } from 'react';
import axios from 'axios';

export default function Home() {
const [blogs, setBlogs] = useState([]);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');

useEffect(() => {
async function fetchBlogs() {
const response = await axios.get('/api/blog');
setBlogs(response.data.data);
}
fetchBlogs();
}, []);

const addBlog = async () => {
const response = await axios.post('/api/blog', { title, content });
setBlogs([...blogs, response.data.data]);
setTitle('');
setContent('');
};

const deleteBlog = async (id) => {
await axios.delete(`/api/blog/${id}`);
setBlogs(blogs.filter(blog => blog._id !== id));
};

return (
<div>
<h1>Blog App</h1>
<form onSubmit={(e) => { e.preventDefault(); addBlog(); }}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Blog Title"
/>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Blog Content"
/>
<button type="submit">Add Blog</button>
</form>
<h2>Blogs</h2>
<ul>
{blogs.map(blog => (
<li key={blog._id}>
<h3>{blog.title}</h3>
<p>{blog.content}</p>
<button onClick={() => deleteBlog(blog._id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}









6. Start the Server



Run your application:




CODE
npm run dev









7. Testing the App




  • You can now add and delete blogs, and all data will be stored in your MongoDB database.



Let me know if you need further details!

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
Sam Altman calls GPT-6 Astra rollout ‘messy’ as enterprise users wait for access
1 Quelle
Swiss government explores replacing Microsoft 365 with open-source software
1 Quelle
What continuous operational resilience looks like under DORA
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Next JS Blog App

Thematisch verwandte Begriffe: Next, Blog · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...