This Next.js example demonstrates how to:
- Load initial data using getServerSideProps
- Keep data fresh on the client after the initial load using
useSWR
The app is live on Vercel for demonstrative purposes.
- A function defined in
/utils/getData.js
returns the data we want in our page. This function is imported and invoked in two locations:- In
/pages/index.js
, invoked ingetServerSideProps
- In
/pages/api/data.js
, invokes in the main request handler function
- In
- In
/pages/index.js
,getServerSideProps
returns the initial data - In the main page function,
initialData
is passed as the value touseSWR
โsinitialData
option, giving an immediate value that we can destructure useSWR
also hasrevalidateOnMount
set to true, so the client immediately refreshes the data from/api/data
when the page is hydrated- You could also configure
useSWR
to refresh on an interval to keep it fresh!