Routing Introduction — Let’s Learn Adonis 5, Lesson 2.0

Tom Gobich | Adocasts.com
7 min readNov 19, 2021

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

Routes are how we can go about defining URLs that will be accessible via our application. So, in order to add a page to our application, we’d need to first define a route for that page. This route definition would register a URL for that page and tell our server what to do when that URL is requested.

The Default Route

By default, Adonis starts our route definitions within the start directory within a file called routes.ts. Out-of-the-box we're provided a single route definition for the welcome page we saw when we booted our application to ensure everything installed okay.

// start/routes.tsimport Route from '@ioc:Adonis/Core/Route'Route.get('/', async ({ view }) => {
return view.render('welcome')
})

Note, in the last lesson we changed this slightly to show how you can expand your HttpContext. I’ve undone those changes here.

So, What’s Happening Here?

First, we’re importing the Route module from @ioc:Adonis/Core/Route, which we'll use to define our routes. Then, we're calling a HTTP method called get off our Route module. This allows us to define a route specifically for get requests (viewing pages, getting info from an API, etc).

The first argument within our get method is the URL pattern we want to match for the route. So, by providing /, we're defining this route for the "home page". If we're running our server locally that's http://localhost:3333. If we were to define a route with a pattern of /test, that route would be accessible via http://localhost:3333/test.

The second argument is a callback function that describes what we want that route to do whenever the requested URL matches this route definition. As we covered in the last lesson, this callback function is provided an HttpContext object unique to a single individual request.

Defining A Route

So, if you have your application running, using the node ace serve --watch

--

--

Tom Gobich | Adocasts.com

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