Define routes dynamically based on dependencies

In v1, it was possible to specifiy routes dynamically based on dependencies like:

@autoinject
export class MyComponent {

	constructor(
		private permissions: Permissions)
	{
	}

    async configureRouter(config: RouterConfiguration, router: Router)
    {
		if (this.permissions.feature1)
        {
            routes.push({
                route: 'route1',
                name: 'route1',
                moduleId: PLATFORM.moduleName('./component1')
            });
        }

        if (this.permissions.feature2)
        {
            routes.push({
                route: 'route2',
                name: 'route2',
                moduleId: PLATFORM.moduleName('./component2')
            });
        }

        config.map(routes);
        config.mapUnknownRoutes(routes[0]);
    }
}

Is there still a possibility to do that in Aurelia 2? Creating routes using a static property or by using the route decorator doesn’t seem to work for this scenario?

Thanks for any help.

AFAIK this kind of conditional route configuration is not supported. However, you can use the routing hooks as described here: https://docs.aurelia.io/developer-guides/routing/router-hooks#authentication-using-lifecycle-hooks

Thanks for your feedback. Isn’t it a bit too simple if routes can only be defined statically? I can imagine many different scenarios where routes depend on dynamic state, especially in larger business applications.

If your need is simply limited to authorized routes then, as I said before, you can use the hooks. Otherwise, for more dynamism, you may use the GitHub - jwx/aurelia-direct-router.

OK, thanks for your help!

1 Like

@Sayan751 I thought the direct router was meant to be v2 core again?

It is, it’s just not there yet. I’m working on it and hope to present news soon. (The direct router supports dynamically configuring routes.)

2 Likes