Created
March 7, 2021 10:16
-
-
Save akellbl4/80ce515641070307279494562289ed62 to your computer and use it in GitHub Desktop.
Code example for the article: "Why I got rid of getInitialProps on my work Next.js project"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function fetchUser(params) { | |
const res = await fetch('https://example.com/api/user', params); | |
const data = await res.json(); | |
return data; | |
} | |
async function fetchUserFromServer(ctx) { | |
const { token } = ctx.req.cookies; | |
const user = await fetchUser({ headers: { Authorization: `Bearer ${token}` } }); | |
return user; | |
} | |
// with server side rendering | |
export async function getServerSideProps(ctx) { | |
const user = await fetchUserFromServer(ctx); | |
return { | |
props: { user }, | |
}; | |
} | |
function Profile({ user }) { | |
return <div>{user.name}</div>; | |
} | |
// with static rendering | |
function Profile() { | |
const [user, setUser] = useState(); | |
useEffect(() => { | |
fetchUser().then((u) => setUser(u)); | |
}, []); | |
if (user === undefined) { | |
// we may create skeleton with react-content-loader here | |
return <div>Loading...</div>; | |
} | |
return <div>{user.name}</div>; | |
} |
The official recommendation is to use getServerSideProps, but I haven't been able to find a "global shared data" method other than getInitialProps.
So there is a lot of confusion
Hey @iiDestiny.
- It's true,
getInitialProps
is the only way to pull shared data, but it's deoptimize your app it the worst way. Then I will call the authorization once for each page?
I won't need in production. First of auth is done per user not per page. Credentials could be stored in cookies of user browser and they are used for identification before response while request and it's true for any way. Only thing that is affected is you need to use auth check on every page. I would suggest to check out https://next-auth.js.org/ if you build auth right in your next app.- The way that suggested by the Next.js team is to request data on every page when you need it.
I also wrote an article about lowering load on your database or backend that provides data: https://itnext.io/fetch-shared-data-in-next-js-with-single-request-833433fa8ed1
Thank you for your reply.
I may have to think about it, I haven't found a best practice solution yet. Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I have a doubt, if not use getInitialProps in _app.jsx to share data for a page.
Then I will call the authorization once for each page? Wouldn't that be cumbersome.