I'm trying to fetch data from an API that varies depending on the URL, trying to do it with withRouter but it seems it won't work inside getStaticProps.
I currently have the following code:
export async function getStaticProps({ router }) {
const pageRequest = `http://localhost:3000/api/posts/${router.query.pid}`
const res = await fetch(pageRequest)
const json = await res.json()
return {
props: {
json,
},
}
}
It's returning:
TypeError: Cannot read property 'query' of undefined
What's the proper way to get the variable in the URL to use inside getStaticProps?
getStaticProps
is called at build time. You don't have router because there is no request performed.
If the dynamic page looks like /pages/[pid].js
you can access pid
in context.params.pid
.
export async function getStaticProps(context) {
const pid = context.params.pid
return {
props: {}, // will be passed to the page component as props
}
}
Note that using static export with dynamic routes requires getStaticPaths
. You'd need to specify all possible IDs upfront, so Next.js knows what pages to generate.
export async function getStaticPaths() {
return {
paths: [
{ params: { pid: '1' } },
{ params: { pid: '2' } }
],
fallback: true or false // See the "fallback" section below
};
}
Also, you can't call Next.js API routes of the same project in getStaticProps
as it's executed at build time (no server is running). You can fetch data directly from the database without an API call.
I would suggest to read Next.js Data fetching for more examples and details.
Alternatively, you can fetch the data on the client side instead.
Fetching data on the client side
getStaticProps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With