Error: A required parameter (id) was not provided as a string in getStaticPaths for /location/[id]

Viewed 1495

im working on a next.js and mongodb website and im following this tutorial exactly but with different files/variable names. i keep running into this error when trying to access the dynamic page : Error: A required parameter (id) was not provided as a string in getStaticPaths for /location/[id]

tutorial : https://www.youtube.com/watch?v=MFuwkrseXVE&ab_channel=Academind Just before 2 hours 40 min

PS deleted db info for security reasons

export async function getStaticPaths(){
    const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
    const db = client.db();
   
    const destinationsCollection = db.collection('destination');
    const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
    client.close();
    return {
        fallback: false,
        paths: destinations.map((destination) => ({ params: {destinationId: destination._id.toString()},
    })),     
    };
} 
2 Answers

Your page is /location/[id] so you need to return an id field in the params objects, for example:

{
    params: {
        id: destination._id.toString()
    }
}

The param you use in the dynamic path matters

in your page location e.g. /location/[anythingInside] you need to ensured whatever is inside your params is same with the dynamic name file which is what inside the braces[] you created e.g. should like this:

{
    params: {
        anythingInside: data.id.toString()
    }
}

Whatever you used when creating the file must be same with the data in the param, for example: path/[anythingInside] and params: { anythingInside: { data }} remember anythingInside must be same with what is inside params.

NextJS is very meticulous with its data fetching functions and you have to be very careful with the way that you return parameters with getStaticPaths() in dynamic routing pages. I believe the problem here is that when you return "params", you store the id of your data (destination._id.toString()) into a JSON variable called "destinationId". However, since the page is called "[id]", Next will be expecting an "id" JSON variable inside of "params". So your final code should look something like this:

export async function getStaticPaths(){
const client = await MongoClient.connect(''); ////////// username and password here for mongo db and db name
const db = client.db();

const destinationsCollection = db.collection('destination');
const destinations = await destinationsCollection.find({},{_id: 1}).toArray();
client.close();
return {
    fallback: false,
    paths: destinations.map((destination) => ({ params: {id: destination._id.toString()},
})),     
};

}

Hopefully this solves the issue!

Related