Recent Post:
Categories:
One of the advantages of Next.js is the ability to interact with your database directly within your application, bypassing the need for separate API layers. Here’s how to do it:
First, set up a connection to your database. This example uses MongoDB.
// lib/db.js import { MongoClient } from 'mongodb'; const client = new MongoClient(process.env.MONGO_URL); export async function connectToDatabase() { if (!client.isConnected()) await client.connect(); return client.db('mydatabase'); }
Fetch data directly within your Next.js pages or components using the connectToDatabase function.
code
// pages/index.js
import { connectToDatabase } from '../lib/db';
export async function getServerSideProps() {
const db = await connectToDatabase();
const posts = await db.collection('posts').find().toArray();
return {
props: {
posts: JSON.parse(JSON.stringify(posts)),
},
};
}
export default function HomePage({ posts }) {
return (
<div>
<h1>Posts</h1>
<ul>
{posts.map(post => (
<li key={post._id}>{post.title}</li>
))}
</ul>
</div>
);
}
You can also manipulate data directly within your page functions.
code
// pages/new-post.js
import { connectToDatabase } from '../lib/db';
import { useState } from 'react';
export default function NewPostPage() {
const [title, setTitle] = useState('');
async function handleSubmit(event) {
event.preventDefault();
const db = await connectToDatabase();
await db.collection('posts').insertOne({ title }); // Redirect or show success message
}
return (
<form onSubmit={handleSubmit}>
{' '}
<input type='text\' value={title} onChange={(e) => setTitle(e.target.value)} placeholder='Post Title\' />{' '}
<button type='submit\'>Add Post</button>{' '}
</form>
);
}
By directly interacting with your database using async/await, you can streamline your application and reduce complexity, making your development process more efficient.