Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Next.js getStaticProps() Function
Next article icon

Next.js getStaticProps() Function

Last Updated : 01 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Data fetching in NextJS: To fetch the data from our own backend or using third-party APIs, we generally use client-side fetching using the fetch API provided by the browser. It fetches the data from the client-side on every request or browser reload.  But NextJS provides us with better ways to fetch the data from the server. It gives us functions to pre-render our HTML on build time or request time. Those functions are

  • getServerSideProps: It renders the data at every request. It runs on the server-side and never on the browser. 
  • getStaticProps: It helps generates the HTML page on the build time (when the code is deployed to production). It’s efficient for static data that changes less frequently.

Next.js getStaticProps() Function: It’s an async function that we export from the page component, used to generate data on the build time. It fetches the data and generates the HTML pages on our server and it caches it. So when we navigate to this page on our client-side, the cached HTML page is served directly to us, which is very useful for search engine optimization (SEO).

The code we write inside getStaticProps is safe and never runs on the browser. So we can also access our database using ORMs like Prisma inside this function as it runs on the server.

Steps to create a NextJS app.

Step 1: Run the following commands on terminal

npx create-next-app <your app name> cd <your app folder>

Step 2: Open your project files on your desired code editor, and run the development server using this command

npm run dev

Now, navigate to https://localhost:3000 to preview

Welcome screen of NextJS

Project Structure: Also, your project folder should look like this,

 

index.js

JavaScript
export async function getStaticProps() {    // Data fetching    return {          // data added inside props will be      // received by page component as `props`     props: {},   }; } 

We return an object from this function where we pass the `props` property with the data that you want to provide to the page component. When should we use getStaticProps?

  • When the data is not changing frequently like a blog website
  •  Data that is coming from any content management system (CMS).
  • To get blazing fast, pre-rendered HTML and SEO friendly.

Let’s see how it works by fetching pokemon data from PokeAPI

Inside the pages folder of your project and in index.js, remove the previous line of code and create a page component and the getStaticProps function.

JavaScript
// Page Component, receiving allPokemons // from getStaticProps export default function Home({ allPokemons }) {     return (         <ul>             { /* mapping all the data inside              an unordered list */}             {allPokemons.map((poke) => (                 <li key={poke.url}>{poke.name}</li>             ))}         </ul>     ); }  export async function getStaticProps() {      // Call the fetch method and passing      // the pokeAPI link     const response = await fetch(         'https://pokeapi.co/api/v2/pokemon/');      // Parse the JSON     const data = await response.json();      // Finally we return the result     // inside props as allPokemons     return {         props: { allPokemons: data.results },     }; } 

Output:

Displayed fetched data inside an unordered list

References: https://nextjs.org/docs/basic-features/data-fetching/overview


Next Article
Next.js getStaticProps() Function

A

arifimran5
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS

Similar Reads

    Next.js getInitialProps
    getInitialProps is a special function provided by Next.js that runs on the server side before rendering a page. This function allows you to fetch data from an external API, database, or any other data source, and pass it as props to your React components. By doing so, you can pre-populate your pages
    5 min read
    p5.js getURLParams() Function
    The getURLParams() function is used to return the current URL parameters a JavaScript object, with each parameter as a separate member of the object. Syntax: getURLParams() Parameters: This function does not accept any parameters. Return Value: It returns an Object of the path parameters. Below exam
    1 min read
    p5.js getItem() Function
    The getItem() function is used to retrieve the value that has been stored using the storeItem() function under the given key name from the local storage of the browser. It returns a null value if the key is not found. The local storage persists between browsing sessions and can store the values even
    2 min read
    JavaScript get Function
    JavaScript get function is used to access the properties of an object using dot notation or square brackets. It allows you to retrieve the value associated with a particular property key and the get function is often used when working with objects that implement JavaScript's getter function. The get
    3 min read
    Underscore _.get() Function
    Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.get() function is an inbuilt function in the Underscore.js library of JavaScript which is used to
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences