Naming, Grouping, & Prefixing Routes — Let’s Learn Adonis 5, Lesson 2.3

Tom Gobich | Adocasts.com
6 min readSep 6, 2022

View all lessons in the Let’s Learn Adonis 5 series here.

As we’re defining our route definitions there’s actually something we can do now to help us vastly cut down on the amount of time needed to refactor in the future anytime we need to change one of our route’s paths. We can do this by naming our routes.

Naming Routes

By naming our routes we can then dynamically generate a URL for that route throughout our application using its name instead of manually supplying the URL. When we do this, should we need to change a route’s path in any way in the future, all we’d need to do is update the route’s definition and all the dynamically generated URLs will auto-update. We won’t need to worry about finding and updating each reference to the route.

We can name a route by chaining an extra method off the route’s definition called as. The as method then accepts as the first argument the name we'd like to give the route.

Route.get('/posts', () => `get all posts`).as('posts.index')

Here I’ve named my /posts route posts.index. We'll get more into generating URLs in the next lesson, but to show you the benefit here, let's generate a URL for this route.

Route.get('/', () => {
const postsUrl = Route.makeUrl('posts.index')
return postsUrl
})
// RETURNS: /posts

Here we’re using the makeUrl method off the Route module to generate a route for our posts.index route. Pretty cool, huh?!

We can name our routes regardless of the HTTP Method the route is using. It’s also default behavior to delimit route names using a period, hence why I’m following the resource.action naming with posts.index. Here's how it looks when we start adding additional routes.

Route.get('/posts', () => {
return 'get all posts'
}).as('posts.index')
Route.get('/posts/:id', ({ params }) => {
return `get post with id of ${params.id}`
}).as('posts.show')
Route.post('/posts', () => {
return 'create a post'
}).as('posts.store')
Tom Gobich | Adocasts.com

Learn AdonisJS, NodeJS, JavaScript and more through in-depth lessons, screencasts, and livestreams at adocasts.com