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
Next.js expects a default export (used to render the page) and a named
getServerSideProps
export to call before rendering. You could do so: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.Get something like this ready
Remove extra and info folders
Put your code inside main.tsx
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