How to Handle Slugs for Index Pages Using Next.js
In there you would check whether it's a project or a blog you want to render. You also need to set up getStaticPaths if you use getStaticProps
https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation
[...slug].js
import { useRouter } from 'next/router'
const Page = () => {
const router = useRouter()
const slug = router.query.slug || []
return (
<p>{slug.join('/')}</p>
)
}
export default Page// index.js
export {default as Blog} from "./blog"
export {default as Projects} from "./projects"
export {default as Press} from "./press"I felt this was a better approach rather than bloating a single file with switches or if/else conditions for a growing number of template variations.I agree. But it does tie you to the filesystem. You might consider setting up dynamic rewrites (https://nextjs.org/docs/api-reference/next.config.js/rewrites ) in next and sanity. That way you could keep your filesystem setup and have more or less dynamic routes. Something like this:
const data = await staticClient.fetch(
`*[_type == "rewrite"]{ from, to }`
);
module.exports = {
async rewrites() {
return data.map((redirect) => {
return {
source: redirect.from,
destination: <http://redirect.to|redirect.to>
};
});
},
};You do need a next rebuild everytime you change a rewrite I think, so that's something you'd have to setup on every rewrite change.
Was this answer helpful?
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.