简体   繁体   中英

Next.js Passing props into pages,

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.

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM