I am trying to learn NextJS and React, by creating an e-commerce site. As it will be connecting to an external db to retrieve stock, that can be updated at any time, getStaticProps is unsuitable. I have tried to implement using getServerSideProps and it works on my index page which just pulls in all the stock from the database, but I am getting a 'module not found error' when using exactly the same function inside the individual product page (apart from adding a filter to find a specific item).
Module not found: Can't resolve 'fs'
According to the documentation I can only export getServerSideProps from pages. index.js and [id].js are both pages but only index.js works.
Here is my index.js (minus the imports)
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const { db } = await connectToDatabase();
var stock = []
const response = await db
.collection("stock")
.find({})
.forEach(function(item){stock.push(convertFromMongoJSON(item))})
// Pass data to the page via props
return { props: { stock } }
}
export default function Home({ stock }) {
return (
<Layout home>
<Head>
<title>{siteTitle}</title>
</Head>
<LandingScreen/>
<Store stock={stock}/>
</Layout>
)
And here is [id].js minus the imports
export async function getServerSideProps({params}) {
var item = null
const { db } = await connectToDatabase();
var stock = []
const response = await db
.collection("stock")
.find({})
.forEach(function(i){stock.push(convertFromMongoJSON(i))})
stock.forEach(function (i) {
if (params.id == item.id){
item = i
}
})
return {
props: {
item
}
}
}
export default function Item({ item }) {
return (
<Layout>
<Head>
<title>{item.name}</title>
</Head>
<div className="row">
....... Lots of HTML ....
</div>
</Layout>
)
}
Any help appreciated as always :-)
EDIT: added the entire error message
./node_modules/mongodb/lib/connection_string.js:5:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules\mongodb\lib\mongo_client.js
./node_modules\mongodb\lib\index.js
./lib\mongodb.js
./lib\items.js
./pages\items\[id].js
https://nextjs.org/docs/messages/module-not-found
But the point is that it works on index.js, so I am unsure why it works on one pager and not the other. Is it because [id].js is for dynamically generated routes?