Multi-File Route Grouping Strategies — Let’s Learn Adonis 5, Lesson 2.4

Tom Gobich | Adocasts.com
5 min readSep 7, 2022

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

I received a great question on the last lesson covering route groups and I wanted to answer it for everyone before moving forward. It’s in regard to having routes split among several different files.

The question was if I have a route group I want to apply to more than one file, do I need to redefine the group within each file? In other words, for the below file structure, in order to have a route group for /api/v1 do you need to define the group in both the posts.ts file and the series.ts file?

start/
├─ routes/
│ ├─ api/
│ │ ├─ v1/
│ │ │ ├─ posts.ts
│ │ │ ├─ series.ts
├─ routes.ts

That would be a pain! Thankfully, the answer is no, you don’t. So long as the code defining a route definition executes within a route group, that route definition will be created as a member of the group.

For example, we can wrap any set of routes within a function then call the function inside two different groups. The result will be the routes defined in the function will be defined twice, once for each group.

function postRoutes() {
Route.get('/posts', () => 'get all posts')
}
Route.group(() => {
// this will define a route for GET: /accounts/:accountId/posts
postRoutes()
}).prefix('/accounts/:accountId')
Route.group(() => {
// this will define a route for GET: /hub/posts
postRoutes()
}).prefix('/hub')

We can then use this same methodology to our advantage when it comes to defining routes to a single group from multiple files.

Using A Function

First, let’s take the above example and apply it to our multi-file scenario. We can wrap the routes we have defined within our posts.ts file and series.ts file in a function that we export. Then, we can import those functions and execute them within our group, like the below.

// start/routes/api/v1/posts.tsimport Route from '@ioc:Adonis/Core/Route'export default function
Tom Gobich | Adocasts.com

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