Migrate from getInitialProps to getServerSideProps in Next.js
Pages in Next.js can use either getInitialProps
or getServerSideProps
to
fetch data. This article will not repeat their documentation, but instead list
relevant differences, and shows example code to migrate from one to another.
This may provide some guidance when choosing or migrating between both methods.
Advantages of getServerSideProps
:
- No need to implement isomorphic code.
- Has
resolvedUrl
(no need to mangle withreq.originalUrl
andasPath
). - Types can be inferred using
InferGetServerSidePropsType
. - Features like
notFound
andredirect
are available. - Preview Mode is available.
On the other hand, it has a few downsides as well:
- The
basePath
is not available. - Return value must be serializable to JSON.
- Requires and exposes the
/_next/data
endpoint. - This
/_next/data
path includes a.json
extension, which may result in unexpected caching (in another layer, like a CDN or API Gateway).
An example Page.tsx
using getInitialProps
:
The same Page.tsx
refactored to use getServerSideProps
:
Notice the differences:
- No need to type
PageProps
separately. - Use
resolvedUrl
directly (no isomorphic logic). - Move the return value to
props
. hasError
is serializable (error
is not).getServerSideProps
is a separate export (not a member ofPage
).