skip to Main Content

What is the Nuxt 3 equivalent way to translate this Next.js page into a Nuxt page?

export const getServerSideProps: GetServerSideProps<PageProps> = async (
  context
) => {
  context.res.setHeader("Cache-Control", "no-store");

  const uri = process.env.MONGODB_URI as string;
  const client = new MongoClient(uri);

  await client.connect();
  const db = client.db("e-commerce");
  const collection = db.collection<Product>("products");
  const products = await collection.find({}).limit(10).toArray();
  await client.close();

  return {
    props: {
      products,
    },
  };
};

const ProductsPage: NextPage<PageProps> = ({ products }) => {
  return <ProductsSlider title="Suggested products" products={products} />;
};

export default ProductsPage;

Please assume that using the mongodb driver (instead of mongose, for example), creating and closing a client for each request, and setting "Cache-Control" -> "no-store" is necessary for this use case.

One way would be to use the mongodb drive in a Nuxt API route and fetch the data from the API with useFetch on the page, but this does not "represent" the Next implementation, because by using a Nuxt API route there would be an additional round trip to the API route to fetch the data.
This does not happen in the Next.js page, as the data is fetched directly in getServerSideProps when the request hits the server.

Is there a way to do this in Nuxt using the mongodb driver, opening and closing the connection to the mongodb cluster during each request?

2

Answers


  1. As I understood, you can have that functionality with useFetch and useAsyncData in Nuxt js.useAsyncData is more like getServerSideProps, but as I understood, it is just intended to fetch data and doing some changes to it, then returning it. You can read more about them in:
    Nuxt Data Fetching

    Better You can do is having a server route with that logic, and then call it with useFetch or useAsyncData, as mentioned here:
    Server Directury

    Nuxt also has Server Components, like in Next, but it is experimental yet:
    Server Components

    Login or Signup to reply.
  2. First, create utils/mongodb.js, we will use this to connect to MongoDB.

    import { MongoClient } from 'mongodb';
    
    export const connectToDatabase = async () => {
      const uri = process.env.MONGODB_URI;
      const dbName = process.env.MONGODB_DB;
    
      const client = new MongoClient(uri);
    
      try {
        // Connect to the MongoDB cluster
        await client.connect();
    
        // Access the specified database
        const db = client.db(dbName);
    
        return { client, db };
      } catch (error) {
        console.error('Failed to connect to MongoDB', error);
        throw error;
      }
    };
    

    then create a Server-Side API Endpoint server/api/products.js

    import { connectToDatabase } from '../../utils/mongodb';
    
    export default defineEventHandler(async () => {
      const { client, db } = await connectToDatabase();
      event.node.res.setHeader('Cache-Control', 'no-store');
    
      try {
        const collection = db.collection('products');
        const products = await collection.find({}).limit(10).toArray();
    
        return { products };
      } catch (error) {
        console.error('Failed to fetch products:', error);
        throw createError({
          statusCode: 500,
          statusMessage: 'Failed to fetch products',
        });
      } finally {
        await client.close();
      }
    });
    

    then Fetch Data in the Nuxt Page Using useFetch

    <template>
      <div class="container mx-auto">
        {{ products }}
      </div>
    </template>
    
    <script setup>
    const { data: products, error } = await useFetch('/api/products')
    
    if (error.value) {
      console.error(error.value)
    }
    </script>
    

    enter image description here

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search