Workaround for dynamic routing in NextJs static export without getStaticProps and getStaticPaths() logic

By
January 30, 2023  · 2 min read

Let’s say that you are working on a NextJs application and you have a requirement to use static export in order to run your dynamic frontend application. To support dynamic routing, you would need to apply the getStaticProps and getStaticPaths logic, you can learn more about this on this stack overflow question.

The above-proposed solution is good if you have a set of dynamic routes let’s say probably 100 dynamic routes. What if your use case includes more than 100 dynamic routes and you want to use the static export feature of NextJs? Don’t worry there is a workaround to everything.

We will use query params for this and the powerful useRouter() hook of NextJs

Step 1: Create a page folder let’s name this one ‘posts’ and create an index.jsx file

Step 2: Write some code so that your content can render on the DOM

Step 3: Make the component such that we add the dynamic content logic

For this demo, we will use JSON placeholder API and we will implement the dynamic logic of showing the todo list data for a specific id (for example: https://jsonplaceholder.typicode.com/todos/1 this API will return us the todo data for id 1 and https://jsonplaceholder.typicode.com/todos/2 will give us todo data for id 2)

As you can see we are extracting the id from the query params so in order to work the URL must be http://localhost:3000/posts/?id=1

Step4: Add the dynamic logic of routing

This code will render the data fetched from the JSON placeholder API on id change in short the page is having the best of both worlds now (Static export with dynamic export)

We hope this blog helped you in some way till then Adios, have a great day and happy learning.