Next JS

How to make a Blog detail page with data fetch from mongoDB in nextJS

To fetch a blog detail page data by ID from MongoDB in NextJS, you can follow these steps:

Step 1: Install the mongodb package in your Next.js project:

npm install mongodb

Step 2: Set up a connection to your MongoDB database. Create a file, let’s say db.js, in the root of your NextJS project:

import { MongoClient } from 'mongodb'; 

const uri = process.env.MONGODB_URI; 
const options = { useNewUrlParser: true, useUnifiedTopology: true, }; 
let client; 
let cachedDb; 

async function connectToDatabase() { 
    if (cachedDb && client.isConnected()) { 
        return cachedDb; 
    } 
    try { 
        client = await MongoClient.connect(uri, options); 
        const db = client.db(); 
        cachedDb = db; return db; 
    } catch (error) { 
        console.error('MongoDB connection error:', error); 
    } 
} 

export default connectToDatabase;

In this example, we use an environment variable MONGODB_URI to store the connection string to your MongoDB database. You can set this environment variable in a .env file or your preferred method.

Step 3: Create an API route to fetch the document by ID. Create a file, let’s say pages/api/blog/[id].js:

import connectToDatabase from ‘../../../db’;

export default async function handler(req, res) {

    const { id } = req.query;

    try {

        const db = await connectToDatabase();

        const collection = db.collection(‘blogs’);

        const blog = await collection.findOne({ _id: id });

        if (!blog) {

            return res.status(404).json({ message: ‘Blog not found’ });

}

        return res.status(200).json(blog);

} catch (error) {

        console.error(‘Error fetching blog:’, error);

        return res.status(500).json({

            message: ‘Internal Server Error’ });

}

}

This API route receives the id as a parameter from the request’s query. It connects to the MongoDB database using connectToDatabase, retrieves the blogs collection, and finds the document by its _id field. If the document is found, it’s returned as a JSON response. Otherwise, a 404 status is returned.

Step 4: In your Next.js page or component, you can fetch the document using this API route. For example, if you have a BlogDetail component:

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

const BlogDetail = () => {
  const router = useRouter();
  const { id } = router.query;
  const [blog, setBlog] = useState(null);

  useEffect(() => {
    const fetchBlog = async () => {
      if (id) {
        const res = await fetch(`/api/blog/${id}`);
        const data = await res.json();
        setBlog(data);
      }
    };

    fetchBlog();
  }, [id]);

  if (!blog) {
    
  return (
      {blog.title} 
      {blog.content} 
      {/* Render the rest of the blog details */}
   ); }; 
export default BlogDetail;

In this example, we use the useRouter hook from Next.js to extract the id parameter from the URL. We then fetch the blog document from the API route (/api/blog/[id]) using

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

sixteen + 7 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top