Skip to content

JSON Data for a Next.js Site

There are two things you need to do, to generate pages based on JSON data.

  • make the data available to your project
  • configure data to be used for new pages

Adding Data

There are fancy ways to do this, but the easiest one is to create a new folder called data in your project, copy your .json file into it, and import it from the place where you want to access it. Something like:

// assuming we are in components/Component.js
import randomDataName from '../data/datafilename';

you can use any variable instead of randomDataName! Make sure that the datafilename is how your .json file is called (so in this case, it would need to be named datafilename.json to work).

Generating Pages

Here's where things get a bit more tricky! But don't worry, it's totally doable.

First, decide where you want your pages to be generated.

If you want a path like /articles/SOMEID, create a folder called articles in your pages folder. Then, create a file called [id].js in that new folder. Yes, the square brackets are important.

This new file needs to contain three core details.

It needs to export a component. This component will get props per page to be generated.

It needs to define a getStaticProps function, as described in the docs.

Lastly, it also needs to define a getStaticPaths function as well. There are examples in the docs. Make sure to return a parameter with the same name as the part of your file name in brackets here!

Gotcha: I thought that it's possible to return multiple things from getStaticPaths, but that turned out to be impossible :( And a hard to hunt down bug.

Think of the getStaticPaths function, as the thing which spits out all pages which need to be rendered. The getStaticProps one returns the right props per page. And finally, the component (function?) returns a page to be rendered.

In Conclusion

With this knowledge, you'll be able to create all the pages you want from your JSON data.

Best of luck, and don't give up if it doesn't work at the first try. It's a fiddly thing, and hard to debug, but doable!