Skip to content

Instantly share code, notes, and snippets.

@akellbl4
Created March 7, 2021 10:16
Show Gist options
  • Save akellbl4/80ce515641070307279494562289ed62 to your computer and use it in GitHub Desktop.
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"
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>;
}
@akellbl4
Copy link
Author

Hey @iiDestiny.

  1. It's true, getInitialProps is the only way to pull shared data, but it's deoptimize your app it the worst way.
  2. 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.
  3. 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

@iiDestiny
Copy link

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