Skip to content

lazy-load express routes #5002

@its-dibo

Description

@its-dibo

I have too many routes in my express app, all of them are loaded when the app started.

I want to load each route only when needed.
so, I tried this approach but with no luck.

let app = Router();

app.get('/collections', getRoute('collections'));
// other routes....

function getRoute(route: string): any {
  let [path, func = 'default'] = route.split(':');

  console.log(`getting route: ${path}`);
  return require(`./${path}`)[func];
}

collections.ts

export default (req,res)=>res.json({ok:1})

when the app starts it logs 'getting route: collections' once and in advance (even if it not accessed).

but I want to load this route only when we access the route 'api/collections'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions