Is there a way to pass data from _app's getServerSideProps to page's getServerSideProps?
My issue is as follows:
I have a custom _app with getServerSideProps. Here I check if the user is authenticated and if so, load the user from DB. Both (isAuthenticated and user) are then passed to the _app's props.
Then I have actual pages. Some of these pages are public and some need authorization, so they have their own getServerSideProps. I would like to access the user data loaded in _app's getServerSideProps from within the specific pages' getServerSideProps in order to decide if a redirect should take place. Otherwise, I'd have to load the user info twice - first on the _app level and then on the page level.
Is there a way to load the data only once (on the _app level) and reuse it on the page level?
// pages/_app.jsx
const App = ...
App.getServerSideProps = async(context) => {
let isAuthenticated = false;
let user = {};
if (context?.req) {
// get token from Cookies, validate token & load user
}
return {
props: { isAuthenticated, user },
}
}
// pages/profile.jsx
const ProfilePage = ...
ProfilePage.getServerSideProps = async(context) => {
// get token, load user - in this step, I'd like to reuse the previously loaded data
if (!isAuthenticated || !user.HAS_SOME_SPECIFIC_PERMISSION) {
return {
redirect: {
destination: '/login',
},
}
}
return { props: {} }
}
Before I finished writing this question, I already decided to get rid of my own auth and use NextAuth.js. However, while I no longer need an answer to this question, it still seems like an interesting "mental exercise" question, so I'm leaving it here... in case anybody needs to pass data from top level getServerSideProps to page level getServerSideProps.