kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

dynamically add routes #117

Closed FredericHeem closed 6 years ago

FredericHeem commented 6 years ago

Would it be possible to dynamically add routes found in a chunk loaded through import? When a route is loaded asynchronously, the router context passed is a copy so the original context cannot be modified at the moment.

frenzzy commented 6 years ago

Basic example (load routes when requested):

const route = {
  path: '/admin',
  children: [], // place for lazy routes
  async action(context) {
    const routes = await import('./admin/routes.js'); // load routes asynchronously
    context.route.children = routes; // dynamically add routes
    delete context.route.action; // execute action method only once
    return context.next(); // go to just loaded routes
  }
}

Also you can dynamically add new routes at any time:

routes.push(newRoute)

Your routes are just plain javascript object and arrays, you can interact with them as you like.

Would you describe your use case more or provide examples, why do you want to modify context?

FredericHeem commented 6 years ago

Thanks a lot, it works perfectly, see the full code at https://github.com/FredericHeem/starhackit/blob/master/client/src/app/router.js