Next.js - Downsides to Handling All Routes with a Single Slug.js File?
19 replies
Last updated: Mar 22, 2021
Curious: Are there drawbacks to just having a single
[[…slug]].jsfile that handles all your routes than manually duplicating logic from file to file? The more I work with Next the less I’m sure the file based routing is worth it.
Mar 16, 2021, 5:31 PM
I do [pageSlug].js for all pages that share the same template as well. I usually have similar pages under /blog/[postSlug].js, and /case-studies/[caseSlug].js
Mar 16, 2021, 7:16 PM
I’m finding so much shared code in all these files though. For example /news/slug.js is going to pretty much the exact same components as /category/slug.js ... so at what point do you just shove everything in one mega catch all file I wonder..
Mar 16, 2021, 7:17 PM
Ha cool, so what do the params look like in ?
export const getStaticProps = async ({ _params_ }) => {
Mar 17, 2021, 8:03 AM
for example that could look like this (file-based):
/news/[categorySlug]/[postSlug]
Mar 17, 2021, 8:03 AM
It requires an array of slugs “parts”. Which you can then use to inform your staticProps query.
Mar 17, 2021, 8:19 AM
I think the only drawback are...• 404 errors work slgihtly different, they go through your optional catch all page, too. Or I had some bugs with notFound: true at least particularly.
• It may be worth checking the webpack bundles before/after. In case they're using each page filesystem name as entry point
• It may be worth checking the webpack bundles before/after. In case they're using each page filesystem name as entry point
Mar 17, 2021, 11:03 AM
I use a catch all
[...slug].jsfor just about every project. the code in the return looks something like this:
return ( <Layout page={data.content} site={doc.site}> {data.content._type === 'page' ? ( <PageContent {...data.content} /> ) : ( <PostContent {...data.content} /> )} </Layout> );
Mar 17, 2021, 6:44 PM
Obviously this example only is using
Pagesand
Posts, but I just add on as needed
Mar 17, 2021, 6:45 PM
Yeah cool. And you don’t see any drawbacks?
It’s something that to me “feels” wrong, but in execution seems so much more right!
Makes me think that Gatsby’s move from a single file to generate all paths, to file based routing, is misguided...
It’s something that to me “feels” wrong, but in execution seems so much more right!
Makes me think that Gatsby’s move from a single file to generate all paths, to file based routing, is misguided...
Mar 17, 2021, 6:51 PM
If things share components all you'd have to do is add an
orstatement where it's checking the type of the
content
Mar 17, 2021, 6:54 PM
I’m doing all my routes in a single
[...slug.js]file now and it’s so clean you could eat off it ✨
Mar 18, 2021, 8:00 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.