Understanding Flat Routing Technique
In today's web development landscape, there are many aspects to consider - from user experience to search engine optimization, and of course, developer efficiency. One approach I frequently employ when setting up routing for a website is known as structural routing.
Take, for example, a URL format like /users/${userId}/posts/${postId}
. This pattern clearly conveys the hierarchy and organization of the data, giving users and search engines an intuitive understanding of the page content.
Lately, though, I've been delving into a trend that's gaining momentum - flat routing. While it's not a brand-new concept, I've been working with it a lot recently, and that's why I’m excited to bring you this article.
Flat routing, unlike its structural counterpart, prioritizes simplicity and brevity in URLs. This approach can bring some intriguing advantages. Instead of a more traditional path, you might see something like /resource/${idOfResource}/
, where idOfResource
is a combined identifier that encapsulates all necessary data to load the content, such as user and post information.
While this example may seem a bit complex, flat routing shines in specific cases. Think of websites where the focus is narrow - like blogs or companies selling particular products, such as cars.
Why go this route? For user-friendliness. For example, it’s easier and more memorable for users to type /bmwx5/ or /tesla3/ rather than /car/tesla/3/. Before you jump to conclusions, I invite you to read further. I’ve gathered some interesting findings on this topic that may surprise you.
So, feeling intrigued? Awesome! Let’s explore the world of flat routing strategies and break down their unique advantages and potential challenges. By the time you finish reading, I’ll have walked you through real-world examples showing where flat routing can shine - and where it might fall short.
The Case From The Project
A while back, I launched my company/community website, GreenOn Software, marking my first venture into building a platform specifically for content creation. It was envisioned as a central hub, independent of social media, where I could easily share my articles, courses, and other resources.
As the project grew, so did the challenges, particularly when it came to scaling. This experience led to the creation of my next project, 4markdown.com. One of the main issues I encountered early on with GreenOn Software was establishing an intuitive and user-friendly routing system.
I structured the URLs into categories, like this:
/articles/${name-of-article}/
/courses/${course-name}/${number-of-lesson}/${chapter-name}/${name-of-article-under-lesson}
As you can see, the second URL is excessively long. While it follows a clear structure, the question remains: is that structure really important for the user? Honestly, it was more about making my life easier as the developer ☜(゚ヮ゚☜).
Over time, I started noticing a pattern: the courses hosted on greenonsoftware.com were attracting very little organic traffic from Google search.
Low Views And Clicks
This trend continued, and even the more trending topics within the courses weren’t generating much traffic. In the span of a year, getting only one click on a page is quite concerning.
Sure, someone might argue that the problem isn’t the URL structure but other elements, like poor content quality, missing keywords, or the numerous other variables that impact search engine performance (we all know Google’s algorithms are a mystery).
To test this theory, I conducted a small experiment. I published the same article on greenonsoftware.com and 4markdown.com. I fine-tuned the grammar using ChatGPT on both, ensuring the keywords remained consistent across platforms.
I manually indexed both articles using Google Search Console, ensuring they were visible around the same time - although, who really knows how those indexing algorithms work?
After waiting three months, the results were eye-opening. The version on 4markdown.com, which had a simplified, flat URL structure, received a far higher number of views and clicks. Here’s the data:
Website | Article Title | URL | Months | Views | Clicks |
---|---|---|---|---|---|
4markdown.com | Crafting useFetch hook | /crafting-use-fetch-hook/ | 3 | 2053 | 252 |
greenonsoftware.com | Creating useFetch hook | /courses/hooks/1/api/creating-use-fetch-hook/ | 3 | 1501 | 102 |
I revised the article grammar slightly to minimize the chance of lower indexing or blockages for publishing the same content on both sites.
While the experiment was small in scope, the difference in engagement between the two sites was quite stark. It strongly suggests that a flattened URL structure could be more effective in boosting site traffic.
Now, I’m not SEO expert, but if you’re interested, I recommend checking out this Quora discussion where some SEO enthusiasts argue their points. Despite their best efforts, even they can’t provide definitive answers, as analyzing URL impact is incredibly difficult (‾◡◝).
To be fair, evaluating URL performance is nearly impossible. You can’t publish the same content at different URLs and expect to accurately compare results. Numerous factors influence clicks and views, and this variability means that conclusions might be misleading. For an accurate answer, we’d likely need insider knowledge from someone at Google.
Nevertheless, it’s hard to ignore the fact that many major platforms, like medium.com, utilize this approach - so clearly, there’s something to it :D.
The Psychological Impact Of URL Length
Every time I receive a lengthy URL, my first thought is that it might be a phishing attack. Perhaps you’ve had the same reaction - long URLs are just plain difficult to trust and read.
Let’s take a look at one of my own examples, like the URL for an article within a course: /courses/hooks/1/api/creating-use-fetch-hook/. It's immediately clear that this type of link can easily overflow in the browser’s address bar, especially on mobile devices or tablets.
Maybe I’m exaggerating a little, but here’s the thing - short, clean URLs are visually more appealing than long, convoluted ones. While this may seem like something only developers notice, it can have a real impact on user perception. Despite my efforts to find research backing this up, the internet seems to lack any in-depth studies.
Know of any? Please feel free to DM me!
Some platforms display pasted URLs in a customized way, while others pull metadata using the Open Graph Protocol to provide context. This makes it hard to predict exactly how your URL will appear. That’s why making URLs clean and easy to read might also improve trustworthiness and encourage more clicks.
Discord Shows Raw URLs
LinkedIn Hides The URL With A Preview
Curious about how others felt, I posted a poll on my LinkedIn. The results were pretty revealing.
As you can see, I’m not the only one who finds long URLs a bit suspicious. Shorter, clearer URLs tend to look more reliable, and people are generally more inclined to trust them at first glance.
Common Flat Routing Pitfalls
While we've discussed two major benefits of flat routing - better SEO (though speculative) and improved readability and trustworthiness - there are also substantial challenges that need to be addressed.
The primary challenge is ensuring your application remains stable and functional (☞゚ヮ゚)☞. For example, consider a scenario where users can create documents, and each document generates a static URL based on its title. Here's a straightforward case:
- A user creates a document titled "Working with Next 14+."
- The app generates a URL: "working-with-next-14."
Simple, right? But what if a user tries something more problematic:
- A user creates a document titled "Articles."
- The app generates the URL "/articles/."
- An error occurs because "/articles/" is already reserved for displaying a list of articles in your routing system.
To prevent these kinds of conflicts, one approach is to add validation rules that require users to include a minimum number of words when creating content. For instance, users might need to create article titles with at least three words.
Meanwhile, the application’s core routes would be limited to a maximum of two words. This ensures that user-generated URLs with three or more words won’t conflict with reserved system routes. Here’s how this could work:
- The user creates a document titled "Articles."
- The app throws an error: "Minimum number of words is 3."
- The user changes the title to "My Article Title."
- The page is generated under "my-article-title."
- The application's article list remains safely under "/articles/."
This method resolves most issues, but maintaining such validation rules across different content types can be tricky, potentially leading to unpredictable behavior. In fact, this is a critical part of any app that requires ongoing monitoring.
const MIN_WORDS_CONTENT = 3;
const MAX_WORDS_URL = 2;
function countWords(text: string): number {
return text.trim().split(/\s+/).length;
}
function validateContentCreation(documentTitle: string) {
const wordCount = countWords(documentTitle);
if (wordCount < MIN_WORDS_CONTENT) {
throw new Error(
`Minimum number of words is ${MIN_WORDS_CONTENT}. Provided: ${wordCount}`
);
}
console.log(`Document "${documentTitle}" passed validation.`);
}
function generateUrl(documentTitle: string): string {
const words = documentTitle.trim().split(/\s+/);
if (words.length > MAX_WORDS_URL) {
words.length = MAX_WORDS_URL;
}
const url = words.join(`-`).toLowerCase();
console.log(`Generated URL: ${url}`);
return url;
}
try {
const title = `Articles`;
validateContentCreation(title);
} catch (error) {
console.error(error.message);
}
try {
const validTitle = `My Awesome Article`;
validateContentCreation(validTitle);
generateUrl(validTitle);
} catch (error) {
console.error(error.message);
}
Now, what if someone forgets the rule and creates a URL shadowing conflict? A fail-fast approach could be useful here:
if (hasDuplications) throw Error(`Hey, your user shadowed the application URL!`);
Another more intuitive solution is to implement a blacklist of restricted routes. This would prevent users from creating resources with URLs that match system-reserved routes, throwing an error if there's a conflict.
const restrictedRoutes = [`dashboard`, `settings`, `admin`];
function createResource(resourceUrl: string) {
if (restrictedRoutes.includes(resourceUrl)) {
throw new Error(
`Resource creation failed: The URL '${resourceUrl}' is restricted.`
);
}
console.log(`Resource '${resourceUrl}' created successfully.`);
}
try {
createResource(`dashboard`);
} catch (error) {
console.error(error.message);
}
try {
createResource(`blog-post`);
} catch (error) {
console.error(error.message);
}
However, this approach feels like building a "backend for the frontend," which demands ongoing maintenance whenever a new route is introduced. Personally, I find the first idea with the validation approach to be more efficient, and it's the solution I’ve implemented on the website you're currently reading.
Let’s take this a step further. Imagine your platform supports various content types - posts, articles, mindmaps, etc. Handling URL duplication across these different content types would require significant validation efforts.
To avoid performance bottlenecks, you'd need to centralize the validation process. Rather than searching individual tables for posts, articles, and mindmaps, you could create a unified "content" table. This table would store mappings of content type, ID, and URL, enabling faster validation but at the cost of database duplication.
Duplicating content in a database - known as denormalization - is a trade-off that sacrifices storage space for improved search performance and faster API response times.
Another approach is to design your database with flat routing in mind. However, this strategy has limitations. You can't always predict future needs, and it’s risky to sacrifice performance just to maintain a clean URL structure. In the long run, that might not be a worthwhile trade-off.
Flat Routing Overview
As we've seen, flat routing introduces both advantages and challenges. Let’s break down the pros and cons based on what we’ve explored so far.
Pros
- Readability
- Clean, concise URLs are easier for users to read, understand, and navigate.
- SEO Benefits
- Shorter URLs might improve search engine rankings, although this is still speculative.
- Trustworthiness
- Users tend to trust simple, clear URLs, which may result in higher click-through rates and better traffic.
Cons
- Risk Of URL Shadowing
- User-generated content can conflict with predefined application routes, leading to potential errors.
- Validation Complexity
- Extra validation rules are necessary to avoid URL conflicts, adding complexity to content management.
- Scalability Issues
- As content types and quantity grow, flat routing can create performance limitations, requiring more careful management.
- Data Duplication
- To maintain good performance, you may need to denormalize the database, which increases complexity in database management.
- Future Flexibility
- Focusing on a clean URL structure today might create limitations or require trade-offs when more critical features need to be introduced later.
Blurry Spots
There are some grey areas when it comes to the overall impact of flat routing, depending on the variety of content types. For instance, if you only have a single type of content, the validation logic and routing system can remain straightforward, resulting in a cleaner codebase compared to structural routing.
However, the complexity increases as more content types are introduced. As a result, flat routing might lead to more complicated code. This is why adding benefits like "simplified code" or "more readable code" to the pros list can be a bit misleading. It really depends on the scope and purpose of the website.
Summary
Flat routing is definitely an intriguing approach that’s worth considering. Like any technical decision, it comes with its own set of pros and cons. No solution should be chosen without careful consideration and refinement.
In my case, transitioning from structural URLs to flat ones proved beneficial. The 4markdown.com website is relatively simple and hasn’t run into the complexities discussed in the Consequences section of this article.
Looking ahead, I plan to add more content types, such as mindmaps, posts, flashcards, and more. This could have been problematic if my database structure wasn’t prepared for it - but I anticipated these changes and designed the content creation process to accommodate them, all while maintaining the flat routing structure.
By now, you should have a clear understanding of when flat routes can be advantageous and when they might not be the best fit.
What I love about software development is the constant balancing act of trade-offs. The ability to make strategic decisions, with long-term goals in mind, is like playing a game where thoughtful planning leads to an application that meets both user needs and technical requirements.