Search code examples
reactjsapinext.jsgetstaticpropsgetstaticpaths

Unable to set up dynamic routing in NextJS for routes from Medium API


I seem to be having issues setting up dynamic routing in my Next app.I'm trying to display my Medium.com posts using the unofficial Medium API. I am able to display a list of cards on my homepage with the posts and I want each one to link to it's corresponding page in my app using the url path from Medium.com.

The API returns the escaped full url of the post on Medium. Eg. "url":"https:\\/\\/medium.com\\/@myprofile\\/some-post-title-81afcccca8a7" I then slice the domain off and just use the path in my Next app's dynamic route. I have added a [...slug].js page inside of a 'post' directory and when I click the link on the post card on my homepage it does try to resolve to mywebsite.com/post/some-post-title-81afcccca8a7 but I get errors.

I'm not entirely sure of the best way to get [...slug].js set up correctly.

In my index.js where I fetch the post details from Medium API I use getStaticProps and inside that I do the following (Medium API requires headers with my API key and host to be passed). The data returned also has to be parsed.

const res = await fetch(url, options).catch((e) => {
    console.error('Error fetching data', e)
    return {
      props: { error: true }, // will be passed to the page component as props
    }
  })

  const data = await res.json()
  var article_ids = data.associated_articles

  var articleDataArr = []

  for (const article_id of article_ids) {
    let article = await fetch(
      `https://medium2.p.rapidapi.com/article/${article_id}`,
      options,
    )
    const articleData = await article.text()
    articleDataArr.push(articleData)

  }

  return {
    props: {
      articleDataArr,
    } 

Can anyone explain how to set up the [..slug].js page?


Solution

  • Are you needing the spread syntax for the posts? If you slice the domain like you said, [...slug] will return ["some-post-title-81afcccca8a7"], as an array with length of 1.

    If you just need article_id passed into your getStaticProps change [...slug] to [slug] and you will get the article_id variable as "some-post-title-81afcccca8a7". Everything else in your implementation looks good, just remove the spread syntax from your filename.