How to fetch data in Next.js using getStaticProps



Image not found!!

In Next.js, getStaticProps is a function that allows you to fetch data at build time and pre-render pages with that data. This is particularly useful for static sites or pages with relatively static content. Here's a step-by-step guide on how to use getStaticProps to fetch data in Next.js:

  1. Create a new Next.js project:

    If you haven't already set up a Next.js project, you can create one using the following commands:

    bash
    npx create-next-app my-nextjs-app cd my-nextjs-app
  2. Create a new page:

    Create a new file in the pages directory. For example, let's create a file named myPage.js:

    jsx
    // pages/myPage.js import React from 'react'; const MyPage = ({ data }) => { return ( <div> <h1>My Page</h1> <p>{data.message}</p> </div> ); }; export default MyPage;
  3. Fetch data using getStaticProps:

    Add the getStaticProps function to your page file. This function should return an object with the data you want to pass to the page component.

    jsx
    // pages/myPage.js import React from 'react'; const MyPage = ({ data }) => { return ( <div> <h1>My Page</h1> <p>{data.message}</p> </div> ); }; export async function getStaticProps() { // Fetch data from an API, database, or any data source const response = await fetch('https://api.example.com/data'); const data = await response.json(); // Return the data as props return { props: { data, }, }; } export default MyPage;
  4. Run the development server:

    Start the Next.js development server to see your changes:

    bash
    npm run dev

    Visit http://localhost:3000/myPage in your browser to view your page with the fetched data.

  5. Generate static files:

    To generate static files for deployment, you can use the following command:

    bash
    npm run build

    This will create a out directory containing the optimized and pre-rendered static files.

Note: getStaticProps is only run at build time. If you need to fetch data at request time (on every user request), you might want to use getServerSideProps instead. Keep in mind that getServerSideProps comes with the trade-off of slower performance compared to static generation.