Introduction
next-modular is a modular architecture framework for Next.js applications. It lets you organize your app into self-contained modules, each with its own routes, API endpoints, and middleware, that are registered and resolved at runtime through catch-all routes.
Why next-modular?
- Self-contained modules Each module defines its own pages, API handlers, and middleware in one place
- Runtime route resolution A single catch-all route delegates to the correct module based on the URL path
- Next.js config extension Modules can declare headers, redirects, rewrites, and webpack config via
nextConfig— merged automatically bywithNextModular - Static generation Modules declare
staticParamsto pre-render pages at build time viagenerateStaticParams - Edge runtime support Use
next-modular/edgefor stateless handlers that run in Edge Runtime with no Node.js dependencies - Configurable Modules can be enabled/disabled and configured per-feature (routes, API, middleware)
- CLI tooling Initialize projects, add registry modules, or scaffold new local modules
How it works
- You define modules using
defineModule(), specifying abasePathand registering route components, API handlers, and middleware - In
modules.config.ts, you list which modules are active - A runtime file (
next-modular.runtime.ts) callsconfigureModules()to register them in a central registry - Catch-all routes (
app/[...module]/page.tsxandapp/api/[...module]/route.ts) import the runtime and delegate incoming requests to the matching module usinghandleRoute()andhandleApiRoute() - A proxy middleware file handles module-scoped middleware via
handleMiddleware()
// modules.config.ts
import { exampleModule } from './modules/example-module/src';
export const modules = [
exampleModule,
// or with config:
// exampleModule({ enabled: true, features: { routes: true } }),
];// modules/example-module/src/index.ts
import { defineModule } from 'next-modular';
import HomePage from './routes/home';
import { helloHandler } from './server/api/hello';
import { middleware } from './server/middleware';
export const exampleModule = defineModule({
name: 'example-module',
basePath: '/example-module',
routes: [
{ path: '/', component: HomePage },
],
apiRoutes: [
{ path: '/hello', handler: helloHandler },
],
middleware: { handler: middleware },
});Last updated on