Building a Daily Journal App with Next.js and MongoDB
November 21st, 2024
Building a Daily Journal App with Next.js and MongoDB
A daily journal app is a great project to track thoughts and activities while learning full-stack development. Using Next.js for the front-end and MongoDB for the database ensures a robust and scalable application. Here’s how you can build one:
1. Project Setup
Initialize a new Next.js project:
bash
Copy code<
npx create-next-app@latest daily-journal
cd daily-journal
Install MongoDB and dotenv for database management:
bash
Copy code
npm install mongodb dotenv
2. Configuring MongoDB
Create a free MongoDB cluster at MongoDB Atlas or use a local instance.
Obtain your connection URI and store it in a .env.local file:
env
Copy code
MONGODB_URI=mongodb+srv://
Create a lib/mongodb.js file to connect:
javascript
Copy code
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
export async function connectToDatabase() {
if (!client.isConnected) await client.connect();
return client.db('journal');
}
3. Back-End API Routes
Create an API route for CRUD operations:
javascript
Copy code
// pages/api/journal.js
import { connectToDatabase } from '../../lib/mongodb';
export default async function handler(req, res) {
const db = await connectToDatabase();
if (req.method === 'POST') {
const { title, content } = req.body;
const result = await db.collection('entries').insertOne({ title, content, date: new Date() });
res.status(201).json(result);
} else if (req.method === 'GET') {
const entries = await db.collection('entries').find({}).sort({ date: -1 }).toArray();
res.status(200).json(entries);
}
}
4. Front-End Implementation
Create a form for journal entries in pages/index.js:
javascript
Copy code
import { useState } from 'react';
export default function Home() {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
await fetch('/api/journal', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, content }),
});
setTitle('');
setContent('');
};
return (
);
}
5. Displaying Entries
Fetch and display entries using getServerSideProps:
javascript
Copy code
export async function getServerSideProps() {
const res = await fetch('http://localhost:3000/api/journal');
const entries = await res.json();
return { props: { entries } };
}
export default function Home({ entries }) {
return (
{entry.title}
{entry.content}
))}
);
}
6. Enhancements
Add authentication with NextAuth.js for personalized journaling.
Use Tailwind CSS or Material-UI for styling.
Implement search and filtering for better usability.
Deploy the app on platforms like Vercel.
This app combines modern technologies to create a functional and customizable journal that’s perfect for both learning and practical use.