next-ssr-example
next-ssr-example copied to clipboard
Next.js SSR with client-side refresh example
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.
How it works
- A function defined in
/utils/getData.jsreturns 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,getServerSidePropsreturns the initial data - In the main page function,
initialDatais passed as the value touseSWR’sinitialDataoption, giving an immediate value that we can destructure useSWRalso hasrevalidateOnMountset to true, so the client immediately refreshes the data from/api/datawhen the page is hydrated- You could also configure
useSWRto refresh on an interval to keep it fresh!