2

I have a layout component which I want to pass to all the pages except the authenticate page.

I have tried using Component.name which works for dev but not for production version.

How can I do this?

  if (Component.name === 'Authenticate') {
    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    );
  }

  return (
    <Provider store={store}>
      <Authenticate>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </Authenticate>
    </Provider>
  );
Xaarth
  • 1,021
  • 3
  • 12
  • 34
  • Does this answer your question? [Next.js Opt out of Layout Component for specific pages from \_app.js](https://stackoverflow.com/questions/66914855/next-js-opt-out-of-layout-component-for-specific-pages-from-app-js) – Shreyas Jadhav Dec 17 '22 at 04:44

1 Answers1

4

You can accomplish this using useRouter inside _app.js (recommended)

import {useRouter} from 'next/router';
function MyApp({ Component, pageProps }) {
  const router = useRouter();
  const {asPath,route,pathname } = router // pick the one that you need
  
  if(asPath === "Authenticate"){
     return (
        <Provider store={store}>
          <Component {...pageProps} />
        </Provider>
     )
  }else{
     return(
       <Provider store={store}>
          <Authenticate>
            <Layout>
               <Component {...pageProps} />
            </Layout>
        </Authenticate>
      </Provider>
     )
  }
}
 

Otherwise you can apply the same logic directly inside <Authenticate> component, and if the current route is "Authenticate" just return the childrens.

Another solution could be to use getInitialProps, but in this way CSR will be disabled and you will rely on the request instead of next.js router:

function MyApp({ Component, pageProps }) {
   const {path } = pageProps 
  
   if(path === "Authenticate"){
      return (
         <Provider store={store}>
           <Component {...pageProps} />
         </Provider>
      )
   }else{
      return(
        <Provider store={store}>
           <Authenticate>
             <Layout>
                <Component {...pageProps} />
             </Layout>
         </Authenticate>
       </Provider>
      )
   }
}
MyApp.getInitialProps = async (appContext) => { 
  return {pageProps : {
    path : appContext.ctx.pathname
  }}
}
Nico
  • 6,259
  • 4
  • 24
  • 40