GitHub GitHub
docs / Merge and Nest

Merge and Nest

LiteNode supports composing multiple router instances into one application. Use merge() to add routes at the same level, and nest() to mount them under a path prefix.

merge()

Signature:

merge(routerToMerge: LiteNode, ...middlewares: RouteHandler[]): LiteNode

Merges all routes from another LiteNode instance into the current one. Optional middleware arguments are applied only to the merged routes.

const userRouter = new LiteNode()
userRouter.get("/profile", (req, res) => res.txt("User Profile"))

const apiRouter = new LiteNode()
apiRouter.get("/data", (req, res) => res.json({ message: "API Data" }))

app.merge(userRouter) // /profile
app.merge(apiRouter) // /data
app.merge(apiRouter, rateLimiter) // /data — with rateLimiter middleware

nest()

Signature:

nest(prefix: string, routerToNest: LiteNode, ...middlewares: RouteHandler[]): LiteNode

Mounts all routes from another LiteNode instance under the given path prefix. Optional middleware arguments are applied only to the nested routes.

const adminRouter = new LiteNode()
adminRouter.get("/dashboard", (req, res) => res.txt("Admin Dashboard"))

app.nest("/admin", adminRouter) // /admin/dashboard
app.nest("/admin", adminRouter, authenticate) // /admin/dashboard — with auth

Middleware Scoping

When merging or nesting with middleware, those middleware functions are scoped to the merged/nested routes only. They do not affect routes defined directly on app.

To prevent a sub-router from inadvertently serving static files from the parent app's static directory, initialize it with "__NO_STATIC_DIR__":

const app = new LiteNode()
const subApp = new LiteNode("__NO_STATIC_DIR__")

app.use(async (req, res) => {
    console.log(req.url) // Global logger — applies to all routes
})

const routeMiddleware = async (req, res) => {
    console.log("Applies only to /sub")
}

app.get("/", (req, res) => res.end("Home"))
subApp.get("/sub", (req, res) => res.end("Sub route"))

app.merge(subApp, routeMiddleware) // /sub — with routeMiddleware
app.nest("/app", subApp, routeMiddleware) // /app/sub — with routeMiddleware
Information Nested LiteNode instances skip static asset serving by default, preventing unintended traversal of middleware in the reverse direction. Sub-routers can still read files from the parent's static directory when merged.

Summary

Method Routes added at Middleware scope
merge(router) Same level as app Merged routes only
nest("/prefix", router) Under /prefix/... Nested routes only

See the Examples page for a full modular application pattern.