oRPC is currently pre-stable, please report any issues on our Discord or GitHub 🚧
oRPC
background

Lazy Router

Enhance the performance of your oRPC router with lazy-loaded routers.

Enhance the performance of your oRPC router with lazy-loaded routers. Lazy routers in oRPC allow you to defer the loading of specific router modules until they're actually needed. This can improve startup times and optimize resource usage, especially for large applications.

Overview

Lazy routers make your application modular and efficient without sacrificing ease of use. Here's how you can set up and use them:

import {  } from '@orpc/server'
 
const  = .<{ ?: { : string } } | undefined>()
 
// Define a router with lazy loading
const  = .({
    : .(() => import('examples/server')),
    // Please use .prefix when you use OpenAPI (Not necessary for contract-first approach)
    : .('/some').(() => import('examples/server'))
})
 
// Use the lazy-loaded router as if it were a regular one
const  = await ..({ : '123' })

Key Points:

  1. Export Requirement: The examples/server.ts file must export a router as the default export. Example:

    import {  } from '@orpc/server'
     
    export default .({
        // something
    })
  2. Seamless Functionality: Once the lazy router is loaded, it behaves exactly like a standard router. You don't need to configure anything extra or worry about limitations.

  3. OpenAPI Compatibility (Optional): Although not required, using the prefix method when defining a lazy router is highly recommended for OpenAPI integration.

     import {  } from '@orpc/server'
     const  = .<{ ?: { : string } }>()
     
     const  = .('/some').(() => import('examples/server'))

    Note: Contract-first approach is optimized by default, so you don't need to use prefix when implementing.

    Adding a prefix helps oRPC dynamically load the router only when it's needed, improving efficiency and alignment with OpenAPI specifications. While optional, incorporating prefixes will greatly benefit your application by streamlining routing behavior.

By using lazy routers, you can keep your application modular and efficient while maintaining the same user-friendly API you're used to.

On this page