react-routernext.jsclient-sidedynamic-routing

How to resolve dynamic routes on client side in Next js framework


I am currently on Next js using full static generation, as I want to serve all my pages from the S3 + cloudfront (no server involved). Next js has good support for this except when it comes to dynamic pages (ex: /posts/:id). All the framework features to solve this type of scenario involve either rendering all passible pages at build time (which is not viable) or having a server to render these pages that have dynamic routes (making, therefore, the site an hybrid app). To continue to be full static I need to have a way around this. In create react app one could use the react-router and resolve the routes on the client side, which is exactly what I want to do for the dynamic routes. But I as far as I know next js and the react-router are not compatible, so apparently that is not an option.


Solution

  • Based on what I know, I think Dynamic Route on SSG is supported. Dynamic route feature is independent of getServerSideProps or getStaticProps. you can just use next/router to get the param you need and render your page accordingly.

    Here is the official example.

    import { useRouter } from 'next/router'
    
    const Post = () => {
      const router = useRouter()
      const { pid } = router.query
    
      return <p>Post: {pid}</p>
    }
    
    export default Post
    

    Reference

    https://nextjs.org/docs/routing/dynamic-routes