One of my favourite additions to Aurelia 2 is app tasks. These are framework-level entry points designed to allow you to run code at different points of the framework life cycle.
Recently, while porting over an Aurelia 1 application to Aurelia 2, I encountered a unique use case where code was being run inside configureRouter to asynchronously fetch data from an API to provide metadata for routes.
In Aurelia 2’s @aurelia/router package, you set routes using a decorator or a static routes property. How on Earth do you run code that touches the routes before the router gets them?
This is where our friend AppTask comes in handy.
By using the AppTask activating
, you can programmatically set routes before the router activates them. This allows you to modify the routes before they are rendered to the user. Simply create an AppTask with the activating
hook and modify the router’s configuration object as needed.
We do this inside main.ts
AppTask.activating(IContainer, async container => { const pageService = container.get(IPageService); const pages = await pageService.getPagesByWebsiteShortcode(); // Do stuff with the pages and user MyApp.routes = [...]; });
One important thing to note is that we have the routes property defined on MyApp, our main application entry point, as a static property. It’s the same approach documented in the official documentation. Because this is inside main.ts
we are already importing MyApp
if you named your component something else, change the name.
So, if you need to set routes programmatically in Aurelia 2 using AppTask, you can use the activating
hook to modify the router’s configuration object before the routes are rendered to the user. This is especially useful if you need to asynchronously fetch data from an API to provide metadata for routes. Remember to define the routes property as a static property on your main application entry point.