0

I have started on Next JS. I am using a common header.js component and included it in _app.js so that it gets rendered all created pages.

Now I want to make my header dynamic, that is navigation items should be fetched from db and rendered. I tried including getServerSideProps() in _app.js, but it is not working. What can be done here?

TIA

Souvik Banerjee
  • 187
  • 1
  • 3
  • 14
  • Does this answer your question? [Trying to fetch data to create a menu, getStaticProps is returning undefined](https://stackoverflow.com/questions/76143966/trying-to-fetch-data-to-create-a-menu-getstaticprops-is-returning-undefined) – Youssouf Oumar May 17 '23 at 12:21
  • While the questions are slightly different, the answer might be helpful. – Youssouf Oumar May 17 '23 at 12:22
  • `_app.js` does not accept a `getServerSideProps` function. You'll have to add your data fetching logic on page level and pass it as props from your page to the component. – Fabio Nettis May 17 '23 at 17:23

1 Answers1

0

You can follow this https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props

Example:

pages/xxx.js

 
import type { GetServerSidePropsContext } from 'next';

const Page: NextPageWithLayout = () => {
  return <p>hello world</p>;
};

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const { resolvedUrl } = context;

  // Fetch data from external API
  const res = await fetch(`https://api/title?path=${resolvedUrl}`);
  const data = await res.json();
  const { title } = data

  // Pass data to the page
  return { props: { title } };  
}

pages/_app.js

import { Fragment } from 'react';
import Header from '@component/Header';
 
export default function MyApp({ Component, pageProps }) {
  const { title } = pageProps;
 
  return (
    <Fragment>
     <Header title={title} />
     <Component {...pageProps}  />
    </Fragment>
  ););
}

edgefish
  • 26
  • 2