Application
Every Megh app is one MeghApplication. You create it, turn features on with use* methods, and start it with run().
import { Megh } from '@meghjs/core';
import { UserController } from './controllers/user.controller';
const app = Megh.createApplication();
app
.useCors({ origin: true })
.useHealth()
.useControllers([UserController]);
app.run(3000);Creating the app
Megh.createApplication(options?) returns the application. It's a singleton: calling it again returns the same app, and the options of the later calls are ignored. Pass every option in the first call.
| Option | Default | |
|---|---|---|
server | Fastify server options (logger, bodyLimit, trustProxy, https, …), passed to Fastify() | |
requestId | {} (on) | Request ID settings. false turns request IDs off. See Logging |
plugins | [] | Plugins to register explicitly |
autoloadPlugins | true | Find plugins among the app's dependencies |
experimental.compiledValidation | MEGH_COMPILED_VALIDATION env, else false | Compile DTO validation once per class. See Validation |
const app = Megh.createApplication({
server: {
bodyLimit: 2 * 1024 * 1024, // 2 MB
trustProxy: true, // behind a load balancer
},
});The Fastify instance
app.app is the underlying Fastify instance. Use it for anything Megh doesn't wrap, such as registering a Fastify plugin:
import etag from '@fastify/etag';
app.app.register(etag);Turning features on
Each use* method returns the app, so they chain. Call them before run().
| Method | What it does | Guide |
|---|---|---|
useControllers([...]) or useControllers({ auto: true, path? }) | Register controllers, or scan a folder (default: every controllers/ folder under src/). Calling it again adds to the list | Controllers |
useMiddlewares([...]) | Global middleware for every route | Middleware |
useAuthentication(Handler) | Sets request.user on every request | Authentication |
useAuthorization(Handler) | Decides access for @Authorized routes | Authentication |
useExceptionFilters(...), useErrorHandler(fn), useErrorLogger(...) | Customise error responses and logging | Error Handling |
useOpenApi(options) | OpenAPI document and Swagger UI or Scalar | OpenAPI |
useCors(options) | CORS, through @fastify/cors | Security |
useSecurityHeaders(options?) | CSP, HSTS, nosniff and other security headers | Security |
useRateLimit(options?) | Requests per client per window, 429 over the limit | Security |
useMultipart(options) | File uploads, through @fastify/multipart | File Uploads |
useStaticFiles(options) | Serve files, through @fastify/static | File Uploads |
useCompression(options?) | gzip / brotli responses, through @fastify/compress | Compression |
setGlobalPrefix(prefix, { exclude? }) | Serve every route under a prefix such as /api | Controllers |
useVersioning(options) | Version routes with @Version(), by URI or header | Controllers |
useEnvSchema(EnvDto) | Validate environment variables at boot | Configuration |
useCache(options) | Memory or Redis cache | Caching |
useMeghORM(options) | Database connection for MeghORM | MeghORM |
useScheduler([...]) or useScheduler({ path }) | Scheduled tasks | Scheduler |
useWorker([...]) | Queue workers | Queue |
useMail(options?) | Send mail over SMTP or a provider's API, now or queued | |
useSocketIo(options) | Socket.IO server | WebSocket |
useHealth(options), addHealthCheck(name, fn) | /health and /ready endpoints | Health Checks |
Integrations are optional peer dependencies. If one isn't installed, the use* call throws with the npm install command you need.
useGlobal
useGlobal sets several features in one call. Each key calls the matching use* method:
import path from 'path';
app.useGlobal({
cors: { origin: ['https://example.com'] },
openApi: { info: { title: 'My API', version: '1.0.0' } },
controllers: [UserController],
middlewares: [RequestTimer],
authorization: AppAuthorization,
multipart: { limits: { fileSize: 5 * 1024 * 1024 } },
staticFiles: { root: path.join(process.cwd(), 'public') }, // must be absolute
});| Key | Calls |
|---|---|
cors | useCors |
openApi | useOpenApi |
controllers | useControllers |
middlewares | useMiddlewares |
authorization | useAuthorization |
multipart | useMultipart |
staticFiles | useStaticFiles |
scheduler | useScheduler |
compression | useCompression (true or options) |
Compression
useCompression() compresses responses for clients that send Accept-Encoding, with @fastify/compress (npm install @fastify/compress). Bodies under 1024 bytes are sent as they are. Options go to the plugin:
app.useCompression();
app.useCompression({ encodings: ['br', 'gzip'], threshold: 2048 });If a proxy or CDN in front of the app already compresses, leave it off.
Running the app
run(port?, options?) starts the app. The port defaults to the PORT environment variable, else 4000:
app.run(); // PORT, else :4000
app.run(3000); // :3000, whatever PORT says
app.run(3000, { host: '127.0.0.1', shutdownTimeout: 20_000 });| Option | Default | |
|---|---|---|
host | HOST or 0.0.0.0 | Interface to listen on |
onListen | Called once the server is listening | |
shutdownTimeout | 10000 | Milliseconds to wait for a clean shutdown before exiting with code 1 |
The host defaults to 0.0.0.0 so the app is reachable inside a container. Pass 127.0.0.1 to accept local connections only. run() can be called once; a second call throws App already running.
What run() does
In order:
- Validates the environment (
useEnvSchema) and every@AppConfig({ schema })class. - Prepares the OpenAPI document, if
useOpenApiwas called. - Runs the
onInithooks. MeghORM connects to the database here. - Finds controllers (with
{ auto: true }), then maps controller and inline routes. - Finds and starts scheduled tasks.
- Installs the error handler and waits for Fastify to be ready.
- Starts Socket.IO, if
useSocketIowas called. - Listens for
SIGTERMandSIGINT. - Starts listening on the port and logs
Application running on <address>. - Runs the
onReadyhooks, thenonListen.
A thrown error in steps 1 to 6 stops startup, and the server never listens.
Lifecycle hooks
Register work to run at each stage of the app's life. Call these before run(); each returns the app, so they chain:
app
.onInit(async () => {
// After the database connects, before routes are mapped and the server
// listens. A thrown error aborts startup.
await cache.warmUp();
})
.onReady(() => {
// The server is listening.
})
.onClose(async () => {
// On shutdown, after the server stops accepting requests.
await metrics.flush();
});Hooks of the same kind run in the order you register them, except onClose hooks, which run in reverse so that things set up last are torn down first. A failing onClose hook is logged and the others still run.
Shutting down
await app.close() shuts the app down, for example at the end of a test. In order, it:
- Stops the HTTP server, waiting for in-flight requests.
- Stops scheduled tasks.
- Closes queue workers.
- Closes the cache, if
useCachewas called. - Runs the
onClosehooks (MeghORM closes its connection in one).
Calling close() twice is safe: the second call waits for the first.
On SIGTERM or SIGINT, run() calls close() and exits with code 0. If shutdown fails, or takes longer than shutdownTimeout, it exits with code 1. See Deployment for running behind a process manager or in a container.
Development and production
app.isDevelopment() is true only when NODE_ENV=development. An unset NODE_ENV counts as production. In production mode, 5xx details are hidden and logs are written as JSON. Set NODE_ENV=development locally to get detailed errors, pretty logs and any docs you gate behind isDevelopment():
if (app.isDevelopment()) {
app.useOpenApi({ info: { title: 'My API', version: '1.0.0' } });
}Megh loads .env into process.env when it is first imported. Set MEGH_DOTENV=false to skip that and manage the environment yourself. See Configuration.