Routes management without any magic strings (Not just another constants file approach)
This package can generate route structures and build routes. It supports sub routes, parameter placeholders and query parameters. It can be used for APIs, SPAs, apps, etc.
Idea 💡
A system with the following features:
- Generate route structures
- Build routes with parameter placeholders
- Build routes with values for the parameter placeholders
- Build routes that can be used in APIs, SPAs, apps, etc.
- Build routes with query strings
For this I developed the @juliushuck/generate-route
package.
Get started 💻
1. Install the package
npm install @juliushuck/generate-route
2. Import the generate function
3. Generate your route structure
The generate function accepts segments and sub routes. Segments can be a static ones or parameter placeholders. A parameter placeholder starts with :
.
4. Build routes
How I use it 🙋♂️
Here is how I use the function when I’m using ExpressJS for the backend and ReactJS and React Native for the frontends.
Route structures
In my current project “Bujus” I have a shared repository between the three parts of the application - An API, a SPA for schools and a mobile app for helpers. This shared codebase contains configs, validation schemas, routes and other utils. Here I have a directory called routes
, in which, I have three files api.js
, school-app.js
and helper-app.js
.
Usage in ExpressJS
Routing with routers
Generating URLs for links in mails, to verify mail addresses, etc.
Usage in ReactJS
Routing with routers
Generating URLs for API calls
Usage in React Native
Routing with navigators
How it works ⚙️
You can read the strongly commented code here: https://github.com/juliushuck/generate-route/blob/main/index.js. It heavily uses the principle of functions generating functions. For the segments joining, it uses the url-join
package and for the query string generation, it uses the query-string
package.
Thank you for reading ✨
Feel free to comment or ask questions below. When you liked the tutorial, follow me on Twitter - I write about entrepreneurship, coding and design.
PS: When you want to translate the package to other languages, hit me up, I would love to help.