I recently tried using getServerSideProps()
. There must be a reason why it was made, but its utility appears to me like that of a normal async
function.
For instance, I am fetching user data with Prisma and NextAuth. I could put the logic I wrote in getServerSideProps()
into just a regular async
function inside my functional component and the effect would be the same.
Thank you in advance!
CodePudding user response:
Indeed having an asynchronous function in your component and calling it inside an useEffect
does the same thing in terms of getting data from an API. The difference is about where the request is made.
The normal one makes it in the browser while getServerSideProps
runs on the server. Here is what the doc says:
getServerSideProps
only runs on server-side and never runs on the browser. If a page usesgetServerSideProps
, then:
- When you request this page directly,
getServerSideProps
runs at request time, and this page will be pre-rendered with the returned props- When you request this page on client-side page transitions through
next/link
ornext/router
, Next.js sends an API request to the server, which runsgetServerSideProps
getServerSideProps
returns JSON which will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you havegetServerSideProps
defined.
getServerSideProps
is preferable for example when making a call to an API with a secret key that you don't want people steal by inspecting the page with the browser development tools.
And there are some cases where you can only use getServerSideProps
. For example if you are using a database package that cannot run in the browser, Prisma
for example:
export const getServerSideProps = async (context) => {
const posts = await prisma.post.findMany();
return { props: { posts } };
};