Skip to content
Advertisement

Is it nessesary to use getStaticProps with json import in Next.js?

I want to render static data that is coming from a JSON or typescript file and display it to the user. Do I have to use getStaticProps or can I simply import the data without getStaticProps? It’s not clear to me after reading the next documentation.

projects.tsx

const projects: [
  {
    id: "6853939";
    name: "Project 01";
    title: "Title 01 ";
    previewImg: "/images/projectThumbnails/image01.jpg";
  },
  {
    id: "6853939";
    name: "Project 02";
    title: "Title 02 ";
    previewImg: "/images/projectThumbnails/image02.jpg";
  }
];

export default projects;

names.json

{
  "names": [
    { "name": "Full Name 01", "age": 34 },
    { "name": "Full Name 02", "age": 22 },
  ],
}

index.tsx

import projects from "../data/projects.tsx";
import names from "../data/names.json";

const IndexPage = () => {
  return (
    <>
      <div>
        {projects.map((i) => (
          <div key={i.id}>{i.title}</div>
        ))}
      </div>
      <div>
        {names.names.map((i) => (
          <div key={i.name}>{i.name}</div>
        ))}
      </div>
    </>
  );
};

Advertisement

Answer

It’s totally up to you which approach you are going to use .

With getStaticProps:

server uses JSON data to inject data and create cache

Without getStaticProps:

JSON file would be injected in client side , without being cached

I prsonally recommend using getStaticProps

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement