Reputation: 33
I have the following function:
export async function getServerSideProps({ req }: any) {
const user = (
await axios.get("http://localhost:4000/api/auth/status", {
withCredentials: true,
headers: { Cookie: `connect.sid=${req.cookies["connect.sid"]}` },
})
).data;
return { props: { user } };
}
Which fetches the users cookie, and then make a HTTP request using it, now I would have liked to do this in my _app.js file - however getServerSideProps() doesn't seem to be useable in there? Essentially, I was wondering how I would execute this function once and not have to include it in every single page file, and then be able to access its output (user) from each page.
Any suggestions would be greatly appreciated.
Upvotes: 2
Views: 1491
Reputation: 449
i had same problem for use getStaticProps. my problem solved with this way.
you can create a lib
folder in project root. and create getServerSide.js
file into lib
.
export function makeServerSideProps(ns = {}) {
return async function getServerSideProps(ctx) {
return {
props: await getUserProps(ctx, ns),
};
};
}
and define function for receive user data getUserProps
.
export async function getUserProps(ctx, ns = ['common']) {
const user = (
await axios.get("http://localhost:4000/api/auth/status", {
withCredentials: true,
headers: { Cookie: `connect.sid=${req.cookies["connect.sid"]}` },
})
).data;
return user;
}
and use makeServerSideProps
into any pages:
import { makeServerSideProps} from 'lib/getServerSide';
import User from 'components/Authentication/User';
const UserPage = () => {
return (
<User/>
);
};
export default UserPage ;
const getServerSideProps = makeServerSideProps();
export { getServerSideProps };
Upvotes: 1