Dynamic server side app routing
Unanswered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
A bit new to Next.js with App router. Which technique is best for server side routing, since getServerSideProps don't work in App folder. In my page.js, I want to get the url path, then render a component depending on path. And if no known path pop a 404. Thanks!
2 Replies
Gray-crowned Yellowthroat
The easiest way to do that is to let the filesystem routing do the work and put each component on its own page, where the folder that it's in is named after the url path that should display it:
but if you're trying to keep your components separate from your routing logic, then your files will look like this
and in
app
| component1
| | page.js (has Component1 in it)
| component2
| | page.js (has Component2 in it)
| layout.jsbut if you're trying to keep your components separate from your routing logic, then your files will look like this
app
| [componentName]
| | page.js
| layout.jsand in
app/[componentName]/page.js you'll generateStaticParams to make the parameters that will be passed to the main component (default export) of the page, and you'll use those params to figure out what component to renderimport Component1 from 'wherever/components/component1.js'
import Component2 from 'wherever/components/component2.js'
export function generateStaticParams() {
return [
{componentName: component1},
{componentName: component2}
]
}
const Page = ({params}) => {
switch(params.componentName) {
case 'component1': return <Component1 />
case 'component2': return <Component2 />
}
}
export default Pageyou could also import dynamically, but I've found that dynamic imports on server components don't hot reload