Require Route Parameter To Start With @ To Match

You can use route matchers to specify requirements on the route parameter. In this snippet, we require our username param to start with the @ character for the route to match.

Published
Jul 11, 23

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Route parameter matchers give you the ability to enforce requirements upon the parameter in order for a given route to match a request.

If you'd like to learn more about route parameters and their matchers, check out our lesson "Dynamic Routing with Route Parameters".

Username Snippet

In the below snippet, the route parameter matcher (defined by the where method) is restricting this profiles.show route to only match if the username param specifically begins with @.

/@adocasts matches route
/adocasts does not match

Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)
Copied!
  • start
  • routes.ts

Purpose

By forcing our username param to start with @, we're able to simplify our profiles.show route, while still making use of other /something routes within our application.

For example:

// will only match if username starts with @
// if username does NOT start with @, this route will be bypassed
Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)

// when the previous route is bypassed, it'll be used to match this route
Route.get('/:slug', 'PostsController.show').as('posts.show')
Copied!
  • start
  • routes.ts

Join The Discussion! (0 Comments)

Please sign in or sign up for free to join in on the dicussion.

robot comment bubble

Be the first to Comment!