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
As I understood, you can have that functionality with
useFetch
anduseAsyncData
in Nuxt js.useAsyncData
is more likegetServerSideProps
, 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
oruseAsyncData
, as mentioned here:Server Directury
Nuxt also has Server Components, like in Next, but it is experimental yet:
Server Components
First, create
utils/mongodb.js
, we will use this to connect to MongoDB.then create a Server-Side API Endpoint
server/api/products.js
then Fetch Data in the Nuxt Page Using
useFetch