How to fetch data in Next.js
There are many ways to fetch data with Next.js. Depending on when you need the data and what you're doing with it, you have options.
Next.js allows you to mix and match Static Generation, Server-side Rendering, and Client-side Rendering to have a genuinely hybrid app.
You can continue to fetch the data client-side to react the same way you do in React.js: hooks, fetch, etc.
Next.js automatically injectsfetchinto your environment. So you do not have to worry about installing libraries likeaxios or Fetch Polyfill
For fetching data ahead of time (for prerendering Pages only) we have:
getStaticProps getStaticPaths getServerSideProps
You cannot use getStaticProps, getStaticPaths,getServerSideProps in components or client-side data fetching.
// /pages/index.js
// The client code
const IndexPage = () => {// jsx }
export default IndexPage
// This function will only ever run on the server.
// The actual code won't even be bundled with the client code above.
export async function getStaticProps() {
// you can do some exciting things here
// for example, file system work or connect to a DB
return {
props: {}
}
}The results of this function are saved into a JSON file and passed as props to the client's component at runtime.
Incremental Static Regeneration revalidate: 1 allows you to update existing pages by re-rendering them in the background as traffic comes in.
Now the list of blog posts will be revalidated once per second; if you add a new blog post it will be available almost immediately, without having to re-build your app or make a new deployment.
getStaticProps with params
getStaticProps with paramsUse getStaticPaths to return the value of the params
Use fallback: true on your return object for getStaticPaths if you have a big site and don't want to statically prerender all items at once, and instead opt in to render some later at runtime via server-side rendering.
getServerSideProp
getServerSidePropgetServerSideProps will be called at runtime during every request.
Last updated
Was this helpful?