Moving & Organizing Routes — Let’s Learn Adonis 5, Lesson 2.2
--
View all lessons in the Let’s Learn Adonis 5 series here.
Although Adonis starts our route definitions within our start directory within routes.ts
, in actuality, it really doesn't care where our routes reside so long as we inform it where they're defined. In this lesson, we're going to cover a few options you have when it comes to structuring your route definitions.
As we go through this lesson it’s important to remember that keeping all your route definitions within the default routes.ts
file is perfectly valid. In fact, that's what I do for most of my projects.
Routes Directory
One option we have is to group routes by topic and place them inside route-specific files inside a routes directory.
So, for a blog, we could have the following files within our routes directory.
/start/routes/auth.ts
for all authentication routes/start/routes/posts.ts
for all post routes/start/routes/topics.ts
for all topic routes
We’d define the routes within these files the exact same as we would within our routes.ts
file.
// start/routes/posts.tsimport Route from '@ioc:Adonis/Core/Route'Route.get('posts', async ({ view }) => {
const posts = [
{ title: 'Post 1', body: '...' },
{ title: 'Post 2', body: '...' }
] return view.render('posts/index')
})
Then, in order to inform Adonis about the routes defined within these files we’d just import them within our routes.ts
file.
// start/routes.tsimport './routes/auth'
import './routes/posts'
import './routes/topics'
With that, all should be working! Of course, since we’re importing them within routes.ts
this means you can really organize them any way you wish so long as they're imported here.
App Modules
Another option we have is to create a Modules directory within our app directory. Then, inside this Modules…