Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Catch-all root level routing in Express.js: considerations and reserving possible routes for future use?

Catch-all root level routing in Express.js: considerations and reserving possible routes for future use?

Problem

I'm using Express.js (3.0) to develop a Node web app; I'd like to have clean URLs for both user profiles:

domain.com/username

as well as for pages each user creates and shares:

domain.com/username/pagename

I really prefer the clean URLs to using something like domain.com/profile/username or domain.com/pages/username/pagename.

The current route configuration for our development is bootstrapped like so:

app.get('/', content.home);
app.get('/about', content.about);
app.get('/signup', users.signup);
app.get('/login', users.login);
app.get('/:user', users.profile);
app.get('/:user/:userpage', userpage.render);

The last two being the catch all routes. Now this works fine, but I'm not sure if it's a bad design or implementation.

More importantly, I'd like to reserve a 100 or so page names for future use, like 'contact', 'careers', 'cancels', 'pricing', etc. I don't plan to launch with these pages, but I'm wondering if I can create a route file that captures these requests and sends them to a Placeholder page, rather than them being evaluated as a user profile or user generated page.

I can obviously prevent those usernames from being created, but there's got to be a creative approach for the routing as well, and understand any other considerations when using catch-all root level routing-- this can cause an unwieldily amount of DB strain due to the user and page look ups for non-existing objects or pages.

Problem courtesy of: Jamie S

Solution

What you could do is something like the following snippet of code. It's in coffee-script, but the general theory is the same.

placeholder = (req, res, next) ->
  res.render 'placeholder'

reserved = ['/contact','/careers','/cancels','/pricing']

each page in reserved
  app.get page, placeholder

app.get '/:user', ....

If you decide you want to add an extra placeholder page, just add it into that array and restart the application.

Solution courtesy of: Menztrual

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Catch-all root level routing in Express.js: considerations and reserving possible routes for future use?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×