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'

--

--

Tom Gobich | Adocasts.com
Tom Gobich | Adocasts.com

Written by Tom Gobich | Adocasts.com

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

No responses yet