Next.js Discord

Discord Forum

Is this the suggested way to redirect to a default landing page?

Unanswered
Kerry Blue Terrier posted this in #help-forum
Open in Discord
Kerry Blue TerrierOP
So this is my directory layout:
└── [year]
    ├── index.tsx
    └── overview
        └── index.tsx


If someone lands on /year/1234 i'd like to redirect to /year/1234/overview. In my [year]/index.tsx I have this simple page:

const { useParams } = createParam<{ year: Year }>()
const Page: NextPageWithLayout<{ year: Year }> = () => {
  const {
    params: { year },
  } = useParams()
  const { push } = useRouter()
  useEffect(() => {
    if (year) {
      push(`/returns/${year}/overview`)
    }
  }, [])
  return null
}

Page.getInitialProps = (ctx) => {
  return {
    year: ctx.asPath?.replace('/returns/', '') as Year,
  }
}
export default Page


Is there a better or preferred way? Additionally, with the path replacing, is there a more "robust" way?

13 Replies

Kerry Blue TerrierOP
Additionally, If I want to have a provider for the rest of the pages within the [year] folder, would i put it part of this layout? Is there a pattern for a provider for nested routes?
Kerry Blue TerrierOP
Yep I'm using the page router.
So what would I return for the page component? Or would there just be no component, and export only the getServerSideProps?
Additionally, do you have any insight around the Provider question for nested routes. I'd like /:year and every other sub route to have access to the Context I define in the provider.

Appreciate the help so far!
Kerry Blue TerrierOP
yep that makes sense 🙂
@Kerry Blue Terrier yep that makes sense 🙂
for the provider, you could wrap the app in pages/_app.jsx
Kerry Blue TerrierOP
But the input to the provider, (the year) is dependant on certain routes?
I guess i could do something in the provider
if (!year) return null
return <YearProvider year={year}>{children}</YearProvider>


But it seems it's a bit out of context?
Question, if i have the provider in the YearLayout for all sub routes, will it re-create a provider when navigating between nested routes? Or will it only create the provider on the initial page load, and then the children just change between sub routes?
@Kerry Blue Terrier But the input to the provider, (the year) is dependant on certain routes?
could you access the params in the provider with the useRouter hook?
 const router = useRouter()
 const year = router.query.year