skip to Main Content

I have this folder structure:

/
 |- ...
 |- pages
     |- info
     |   |- main.tsx
     |- extra
         |- main.tsx

Both /info/main and /extra/main routes render the same content, including the getServerSideProps. My question is how to implement the logic in one of them and reuse it in the other, so the code is not duplicated. I tried in extra/main.tsx:

import MainCmp from '../info/main';
export default MainCmp;

and it works, but it doesn’t execute getServerSideProps. Also tried with rewrites:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/extra/main',
        destination: '/info/main',
      },
    ]
  },
}

and works again, but then the url is /info/main instead of /extra/main when loading some extra…

Any hint on how to solve this?

2

Answers


  1. Next.js expects a default export (used to render the page) and a named getServerSideProps export to call before rendering. You could do so:

    //extra/main.tsx
    
    import MainCmp from '../info/main';
    export { getServerSideProps }  from '../info/main';
    export default MainCmp;
    

    You could also use a helper function to be called by the getServerSideProps of each page, and a component that gets the data and displays it to be called by each page component.

    Login or Signup to reply.
  2. Get something like this ready

    Slug

    Remove extra and info folders

    Put your code inside main.tsx

    import { useRouter } from "next/router";
    
    const Slug = () => {
        const router = useRouter()
        return (
            <h1>Slug: {router.query.slug}</h1>
        )
    }
    
    export const getServerSideProps = () => {
        console.log('Slug Page')
        return {
            props: {}
        }
    }
    
    export default Slug
    

    Browse http://localhost:3000/extra/main (Prints Slug: extra)

    Browse http://localhost:3000/info/main (Prints Slug: info)

    All should be redirected to the same content with different outputs

    Read more on https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search