Declarative Routes for NextJS and React-Router: DRY Routing
Why settle for hard-coded link strings and URLs for fetch calls? Let's build a declarative routing system on top of NextJS's router (and the React-Router), to give us write once and never change routing.
Code: github.com/jherr/nextjs-decla...
NPM: www.npmjs.com/package/declara...
👉 Upcoming NextJS course: pronextjs.dev
👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
👉 Discord server signup: / discord
👉 VS Code theme and font? Night Wolf [black] and Operator Mono
👉 Terminal Theme and font? oh-my-posh with powerlevel10k_rainbow and SpaceMono NF
00:00 Introduction
1:50 Example Application
3:13 Declarative Routing File System
4:11 Declarative Routing Indexing and Layout
5:39 Handling Query Strings
7:03 Builder Features
10:03 Search Routes
11:53 Outroduction
You are the tech consultant of my company. 🤣
I did not realise how much react routing sucked until I watched this video, I have to try this immediately. Calling out that you can incrementally adopt is what really sold me 🔥
This is not React, it's Next. If you are using just React try Tanstack Router.
Very elegant solution. Simple yet powerful.
As usual, every video from you is awesome, I become a better developer every week thank to your channel, I really appreciate your work.
Awesome video, Jack. Thank you!
Awesome, looking forward to digging in...
WOooo amazing!! looking forward to check it
This looks great. Thank you!
This is a really good idea. Taking this for my projects ❤
Really nice solution, I will give it a try! Thank you, great work here 👍
Awsome!! I need this in my app. I am done writing links everywhere.
Nice. I'm surprised this doesn't exist already
Right?!?
top tier content. who even needs trpc or tanstack router anymore
is that a joke?
@@vty4261no. TS has enough features on its own to be a type-safety contract generator. both trpc and ts-router are basically just doing the same thing with more complexity
@@vty4261it definitely is cos wtf? Did he really said Tanstack for what?
Wtf you mean??
@@Osirisdigitalagency it's not a joke, this is basically all tanstack router and trpc are doing is generating typescript contracts. they basically serve no other purpose than what was shown in the video if you can achieve this with plain TS why would you need a library for it
I'll start using this on my app right a way thanks! 🎉
I am looking to do the same thing for remix! Awesome video as always!
Feel free to jump in and contribute. There is a React-Router version there already, but it only works with the routes object declaration usage of React Router. So we'd need a version that would work with Remix's file routing. There are just so many variations of router setup out there.
Looks cool, will try it in my next todo app
That’s another perfect video 🎉
You are a godsend in the community
Great content! 👏👏 thank you! 🙏
That's actually very interesting
Really nice! Thanks
this is VERY useful 🙌🏼🙌🏼🙌🏼
Thank you Jack!
This declarative routing really takes any project to the next level! I have a question about the example using getPokemonSearchAPI. Shouldn’t we first validate the backend response using zod’s parse or safeParse to prevent any backend model changes from breaking our application? Thank you!
I know it’s zoomed but your terminal looks like a pack of m&ms. Nice video btw 🎉
Do you have any video with your vscode theme, icons, font, terminal, etc. ?
Dang this really is cool.
Great as always ❤.
Ver nice, this is a real new approach right?! I like it!
Kinda? It's built on top of what Flightcontrol did, but substantially improved. The scanner/builder is new, the whole API wrapping system is new, and the support for other types of routers is new. The React-Router support has some crazy hierarchich TypeScript generics in it that were fun to figure out. I should do a video on that. Arguably the React-Router implementation is even cooler since you can just change an entry in a table and all the routes change automagically. I don't know, or really even think, that this will be the end solution in this space. I just wanted to push the ball forward a little to see where other folks take it.
Amazing 🔥🔥
Looking forward to contribute! Which repo is it? Found the demo repo but not the package one 😅
You are awesome 👌
Thanks for this. May I ask how you customized your Shell? Thanks!
It's oh-my-posh on top of oh-my-zsh.
@@jherr Thanks!
This reminds me of the work done by ethan on next-typesafe-url ( cant paste links ) :( ! Super awesome stuff and works pretty well in my projects to solve the same problem :)
I think it is awesome
Ok, this is dope. The one thing that I would've preferred is if all the links were exported from one object. So something like `Link.Home` and `Link.Search` while the APIs would be something like `API.Search` and `API.Edit`, that way everything feels a bit more centralized
Hmmm... Could be a cool option.
I've always done that by myself on my projects, it's one of the reasons I don't like Next directory based router. In the React standalone days, I would create all the routing from an constant object. If one route needed to change you only had to change that object, with Next you can't do that, you need to change the names and location of folders and in the code as well.
This is awesome! But one thing I’m thinking is that generally the routing doesn’t need to change often on the app, and if it does then imo it’s a bigger issue with the application
In evolved apps I think you are right. In early apps for small teams this could be a real ass-saver.
Awesome! Can you please make a video about Vercel's Generative UI. 🙏
Any vidoe or course on how we can build such thing it doesn't have to be a strong as the original library... That can be the ultimate senior front end video ever posted on KZhead Whag a flex having such project sitting on my portfolio. Hope my comment get noticed by the author.
This is pretty cool! How do you handle error handling with API routes?
It's a promise, you can do a catch on it to catch the errors.
Hi Jack, great tutorial, one thing I noticed the package doesn't take into account is folder groups. I have grouped features of the app under folder like `(marketing)` or `(users)` under app folder and the routes created are `/(marketing)/(home)` even though it should be `/` - so perhaps ignoring the folder groups would be a great addition to the package
Feel free to contribute that. Or add an issue and someone else might pick that up. I'll definitely be working on this more, but at the moment the course is my daily top priority.
@@jherr yes I can look into that, I couldn't find the repository for declarative routing - can you provide the link?
@@hassan.tl94 github.com/ProNextJS/declarative-routing
That's a really nice system, I was curious to dig into the project's code to better understand it but it seems you don't ship the non uglified code of declarative-router, that's a curious choice..? 🤔
Here is a link to the repo: github.com/ProNextJS/declarative-routing
@@jherr thanks, totally missed that 😅👍
what's wrong with a recursive sed -i substitute command? It wil take much longer to figure out what's going on if I find this declarative routing stuff in an old project two years from now... AND to remember to have to run some binary with a specific pnpm version and AAARGH...
Well, it's not a binary, and all of the source is in your source, but if you don't want to use it that's totally fine by me.
@@jherr thanks... sorry I had a stressful day and may have overreacted
I used to do an object in a config file which contained all routes
That's how we do it,, has always worked well. This package does neat things, I think it would be useful for taking over maintenance of an app that has all of the links hardcoded. Not sure I'd ever use it in a new project, though.
I like it, I will try it in my project, but can it be used on server actions?
I don't see why you couldn't use it in a server action, but server actions don't need them since NextJS handle the routing on that automatically.
Oh I get it 🤣
He is GOLD 🪙
Hi Jack, my index.ts is not correctly making the imports because it's using backslashes instead of forward slashes.
Are you on windows?
@@jherr yes I am Jack
I usually put my routes in variables... then I do just const userRoute = 'user/:id'; and then userRoute.replace(':id', user.id)
Why not create a function that returns the string? const createUserRoute = (id) => `user/${id}`;? Seems more sensible compared to userRoute.replace because you don't have to know what specific string you have to replace, you just pass in arguments.
This is great work. Can it be used with tanstack-router with vite
With Vite you can use React-Router. Tanstack is a little tricker, I would need to work with that team to figure out integration into TSR and their Vite plugin.
@@jherr thanks please
@jherr I will check it out with react-router
Sorry to highjack this video, Jack. I've got a request that I'm sure you're capable of answering. With TRPC and Prisma, do you have a recommendation on how to do multivariant products design, such as size, color, or any other custom variant group? I'm struggling a lot with how to handle it when not having concrete tables such as size, color, etc. I've looked into the EAV design theory, but can't seem to apply it with "pivot tables" using Prisma.
Feel free to jump on the Discord server and ask your question there. Please read and follow the #rules before posting, it's an all volunteer support service.
🔥LGTM
I prefer to use function that return url So if I need to give this url to custom component with href or to navigate, I can
Then just call the function directly and it will return the URL, as shown in the video.
I think something like this already exists for Next.js, IIRC it's called next-typesafe-url. As for pure React, tanstack router is (IMO) a more reliable option.
Interesting, I still have to manage that URL as a string every time I use the link though. Plus from the little video attached to the github page the resultant code to build the href is pretty long. Also, it only handles page routes and not API routes.
@@jherr Fair enough
Where is the repository link for this project?
github.com/ProNextJS/declarative-routing
Links from the "Installation" section of NPM lead to a 404 page.
What is optimal way to keep main process and watchers from all different tools active without opening 100500 terminals? Can you make video on this topic?
Use the concurrently library.
how about using it with Nx monorepo?
I don't see why that would be a problem, you'd just have to launch it as in the context of the repo. It just runs `pnpm add` (or whatever your package manager is) so hopefully that works. I don't like that NX removes package.jsons.
I am gonna give it a go, keep you posted
if you have to change your routing at a point where you have tons of references you have a problem anyways.. breaking links on the customer side
The video is nice, but I don't see the need for the library. Typically, I store the endpoints in a standard JSON file and import them wherever necessary. If I need to change an endpoint, I only update the JSON file, and the changes are reflected everywhere. This keeps the syntax of routing components consistent and avoids confusion for anyone who works on the project later.
Who is your favorite pokemon and what makes it special?
Gumshoos. He's terrible and he looks a little like me.
Its failing with NextJS latest version 14.2
Dr. Build
Rly you didn't left the link on NPM, why?
Good point: www.npmjs.com/package/declarative-routing
@@jherr TY. I meant about description below the video Have a good one!
I added it there too ty
I hate this in react, magic strings everywhere.. I just wanted the native router to support route tags so you define route strings once but links can point to route tags.. good alternative but think the main Devs should have done a lot better
Your course status?
Going really good. Release late this month or early next. I'm really proud of it.
@@jherr That's really exciting!
How can this use dot notation in a server component wtf?
Crap, that's true. I forgot about that.
@@jherr so how is your example not crashing? 😅
@@SanderCokart I've forgotten the constraint. It might fail on build. I'll check it out. Either way, you can fall back on using the string variant. Or... you can change the code so that the component is the primary export, so it would be `` instead. The code is just copied into your repo like shadcn.
@@jherr it should've failed on dev too.
i am missing readme and examples
The validation is a bit unnecessary given it's used in the same application. Typescript covers most of that use case
Which validation part?
This is cool, but for the love of god , do not add this to your company’s nextjs project. It’s like react devs are plagued with the curse of abstracting everything, on top of that this adds another build step and another dependency to the mammoth that is the node modules folder.
Except that this doesn't actually add to the node_modules folder beyond zod and and the URL parser.
@@jherr happy to be proven wrong.
Awesome solution Jack, I really appreciate you hard work🫡