Server API and application runtime
The server API is the HTTP boundary between Immich clients and the services that manage media, users, access, and server state. A supervised NestJS application starts the API worker, applies shared request rules, exposes controller routes under /api, and serves the web client and real-time events from the same runtime.
Runtime composition
The runtime separates process control from application work. This lets Immich start the API, maintenance work, and background work as distinct workers while keeping their shared services and data rules in one NestJS module design.
Worker model
The top-level process in server/…/main.ts supervises the enabled workers. It starts the API as a child process and starts the other workers as worker threads. Maintenance mode starts only the maintenance worker. A normal start waits for the maintenance database lock before it starts the configured workers.
The supervisor treats worker exit as an application event. A planned restart waits for all workers to stop and then boots them again. An unexpected failure ends the application, and a failed non-API worker also stops the API so that clients do not use a partial server.
References: server/…/main.ts• L13-43 server/…/main.ts• L66-92 server/…/main.ts• L98-161
Nest application modules
server/…/app.module.ts defines the NestJS composition for each worker role. ApiModule combines the controller set with shared repositories and services, database access, job queues, schedules, telemetry, authentication, and request middleware. The maintenance and microservices modules reuse the shared layer but expose different worker responsibilities.
The shared module lifecycle connects services before requests arrive. It installs service handlers for events and queues, configures WebSocket authentication, records bootstrap and shutdown events, and tears down telemetry when the module closes.
References: server/…/app.module.ts• L43-64 server/…/app.module.ts• L69-110 server/…/app.module.ts• L112-151
HTTP server boundary
The API worker turns the Nest module into an Express HTTP server. Startup sets the server-wide request policies before it listens for Immich web, mobile, and external API clients.
API startup
server/…/api.ts creates the ApiModule as a Nest Express application. server/…/app.common.ts then installs logging, proxy handling, security headers, cookies, body parsing, compression, the /api global prefix, WebSocket support, Swagger documentation, static web assets, and server-side rendering.
The API starts on the configured host and port. It allows long-running requests for media work and reports its URL, version, and environment after the listener is ready. The public discovery and CSS routes remain outside the /api prefix because clients and browsers use them as fixed paths.
The startup path is summarized below.
flowchart LR
S[Supervisor] --> W[API worker]
W --> N[Nest ApiModule]
N --> C[Express configuration]
C --> P[Request policies]
C --> R[Routes under /api]
C --> H[Web assets and SSR]
C --> L[HTTP listener]
References: server/…/api.ts• L9-31 server/…/app.common.ts• L24-68 server/…/app.common.ts• L70-102 server/…/constants.ts• L60-64
Web client delivery
The API process serves the built web assets when the configured web root exists. It gives immutable application assets long cache lifetimes and supports compressed forms. For browser GET and HEAD requests that are not API or excluded paths, ApiService returns the web application's HTML shell.
Shared-link pages use the same HTML response with link-specific metadata. The server checks the share key or slug, adds safe Open Graph data when the link is valid, and returns a not-found response when it is not. Requests that do not accept HTML do not enter this browser page flow.
References: server/…/app.common.ts• L70-89 server/…/api.service.ts• L39-100 server/…/app.controller.ts• L6-27
Real-time connections
WebSocket support extends the HTTP API with live server events for connected clients. The API uses the same authentication service as HTTP routes and connects Socket.IO through Redis so that events can reach clients when more than one server process handles connections.
References: server/…/app.module.ts• L87-97 server/…/app.common.ts• L65-67 server/…/websocket.adapter.ts• L8-19
Controller and API surface
Controllers are the public API boundary. They map HTTP paths and methods to application services, while DTOs describe the data that clients send and receive. The controller registry in server/…/index.ts is the source of the API module's route set.
Route domains
The API groups routes by the product capability that owns the client contract. The two child pages describe the largest domains in more detail.
| Domain | Main client purpose | Related page |
|---|---|---|
| Asset and media | Upload, browse, search, download, stream, edit, and process assets | Asset lifecycle and media processing |
| Identity and sharing | Sign in, manage sessions and users, authorize clients, and share albums or assets | Identity, access, and sharing |
| Server and administration | Read server state, manage configuration, run maintenance, inspect jobs, manage libraries, and administer the instance | This page |
The remaining route groups support product views and related data such as albums, people, memories, tags, stacks, workflows, notifications, maps, and synchronization. They use the same authentication, validation, error, and OpenAPI rules as the larger domains. These routes let clients organize assets, manage face and person data, run user workflows, and inspect the results of those workflows. People routes also cover face assignment, person merging, and controlled access to people data.
References: server/…/index.ts• L1-95 server/…/asset.controller.ts• L33-65 server/…/library.controller.ts• L22-119 server/…/memory.controller.ts• L23-135 server/…/person.controller.ts• L45-61 server/…/person.controller.ts• L100-175 server/…/person.controller.ts• L177-257 server/…/stack.controller.ts• L17-110 server/…/tag.controller.ts• L24-140 server/…/workflow.controller.ts• L25-131 server/…/constants.ts• L145-210
Endpoint contracts
Controller methods define a contract for both clients and generated API documentation. @Authenticated() declares whether a route is public or needs a user, admin role, shared-link context, or permission. @Endpoint() adds the operation summary and API history. DTO schemas then describe valid input and output values.
Controller contracts can include bulk operations, file responses, scoped permissions, and version history. Asset, memory, stack, and tag routes expose related operations that let clients group and update assets without reducing every action to a single-asset request. People routes protect face assignment, merge, and sharing operations with distinct permissions. User, session, and API-key routes keep account and client access under explicit permissions. Library and administrator routes add an admin boundary for instance-wide actions. Workflow routes expose both user-owned workflow data and a public trigger list.
Many controllers keep older update paths as hidden compatibility routes while clients move to newer paths. The same contract records destructive actions, such as API-key rotation or session removal, as distinct operations so clients can handle their effects correctly.
The people API illustrates this contract. It supports permission-scoped list, create, update, delete, statistics, thumbnail, face reassignment, merge, and people-access operations. Its current bulk merge route replaces a deprecated path-based merge route, while a hidden patch route keeps the version-three update path working. These routes return structured data or file responses through the same controller boundary as the rest of the API.
For example, the server controller exposes public health and version information while protecting server statistics and license changes with permissions and admin checks. The changed controllers use the same contract for asset metadata and edits, library scans, person thumbnails, user profile images, memory assets, stack membership, tag assignment, and workflow logs. Swagger publishes the resulting contract at /api/doc, /api/spec.json, and /api/spec.yaml. Development mode can also write the cleaned OpenAPI document for client generation and review.
References: server/…/server.controller.ts• L24-40 server/…/server.controller.ts• L66-86 server/…/server.controller.ts• L129-183 server/…/api-key.controller.ts• L16-107 server/…/asset.controller.ts• L99-261 server/…/library.controller.ts• L85-119 server/…/memory.controller.ts• L107-135 server/…/person.controller.ts• L55-61 server/…/person.controller.ts• L66-175 server/…/person.controller.ts• L177-257 server/…/session.controller.ts• L21-102 server/…/stack.controller.ts• L101-110 server/…/tag.controller.ts• L57-140 server/…/user-admin.controller.ts• L26-187 server/…/user.controller.ts• L44-248 server/…/workflow.controller.ts• L47-131 server/…/decorators.ts• L160-176 server/…/misc.ts• L320-372
Request policies
Every API request passes through shared policies before the controller service runs. These policies keep authentication, input shape, file handling, logs, response shape, and error reporting consistent across route domains.
Authentication and authorization
The API uses AuthGuard as a global guard. A route must declare @Authenticated() so the guard knows how to handle it. Public routes continue without a user. Other routes pass request headers and query values to the authentication service, which checks the session, bearer token, API key, admin context, shared-link context, and required permission as appropriate.
The guard places the authenticated user on the request for controller and service use. The same decorator also describes the accepted security methods and permission metadata in the OpenAPI contract.
References: server/…/app.module.ts• L45-53 server/…/auth.guard.ts• L18-56 server/…/auth.guard.ts• L89-123
Input and output validation
ZodValidationPipe validates request data before controller logic, and ZodSerializerInterceptor checks response data on the way out. Shared schemas in server/…/validation.ts give route DTOs common rules for IDs, dates, email values, coordinates, booleans, file names, and partial updates.
This boundary rejects invalid data early and keeps client-visible shapes stable. Multipart fields can also contain JSON text, so the shared parser validates that text before the route receives it. People requests show the same contract in practice: IDs must be valid UUIDs, update payloads need an allowed field, and shared person and user lists must not contain duplicates.
References: server/…/app.module.ts• L45-51 server/…/validation.ts• L35-75 server/…/validation.ts• L97-177 server/…/validation.ts• L213-250 server/…/person.controller.spec.ts• L27-45 server/…/person.controller.spec.ts• L85-109 server/…/person.controller.spec.ts• L182-197
Error responses
Known HTTP errors keep their status and response data. Validation errors use a common Validation failed shape with the Zod issue list. Unknown route errors are logged and returned as a generic internal-server error, which prevents internal details from becoming part of the client contract. Responses also include a correlation ID for tracing a request through server logs.
References: server/…/error.interceptor.ts• L14-37 server/…/global-exception.filter.ts• L10-71
File upload boundary
The API treats uploads as a stream boundary rather than as ordinary JSON bodies. The upload interceptor selects the asset or profile handler, checks whether the file is allowed, writes it to managed storage, and records its size and checksum for the application service.
For asset uploads, a checksum lookup can return a duplicate response before the normal upload handler runs. Empty files and interrupted requests become controlled upload errors, so the client receives a clear result and the server can clean up the partial file.
References: server/…/file-upload.interceptor.ts• L39-87 server/…/file-upload.interceptor.ts• L89-151 server/…/asset-upload.interceptor.ts• L10-26
Background and service boundaries
The API is the request-facing part of a wider application runtime. It calls shared services for immediate work and uses queues, events, storage, the database, and real-time connections when a task must continue beyond one request.
Asynchronous work
BullMQ queues and the microservices worker provide the path for long or scheduled work. The API module registers the queues and exposes queue-related controllers, while shared lifecycle code connects services to job and event handling. This keeps client requests responsive while media analysis and other work continue in the background.
References: server/…/app.module.ts• L58-64 server/…/app.module.ts• L82-96 server/…/microservices.ts• L12-31
Observability and shutdown
The runtime starts telemetry when metrics are enabled and uses a shared logger for startup, request completion, and route errors. Module shutdown emits an application event and tears down telemetry. The API also records request method, URL, status, duration, and a redacted form of request data.
References: server/…/app.common.ts• L17-22 server/…/app.module.ts• L82-102 server/…/logging.interceptor.ts• L19-45
Change checklist
When these files or sections are changed, remember to consider these:
- When adding or moving a route, update the controller registry, its
@Authenticated()contract, endpoint history, and the generated OpenAPI operation. - When changing a route's version or replacement, keep deprecated compatibility paths and their replacement operation aligned.
- When changing the
/apiprefix or excluded paths, check API discovery, browser SSR, static asset delivery, and client URLs together. - When changing permissions or route context, update the authentication metadata and the client-facing security information generated by Swagger.
- When changing shared DTO rules, check UUID, uniqueness, and partial-update constraints in every controller that uses the schema.
- When changing a controller route, check its service boundary, permission, response type, and any bulk or file-response behavior as one client contract.
- When changing user, admin-user, session, or API-key routes, check that account ownership and admin checks still match the access model described by the identity page.
- When changing asset-related grouping routes for memories, stacks, tags, or people, check that their asset ID operations remain consistent with the asset lifecycle API.
- When changing workflow routes, check the public trigger contract separately from authenticated workflow, share, and log operations.
- When changing upload field names or checksum behavior, check the multipart interceptor, asset service contract, and duplicate-upload response.
- When changing worker names or start rules, keep the supervisor lifecycle, worker module token, telemetry port, and failure behavior aligned.
- When changing WebSocket authentication or event delivery, check both the API worker and the Redis adapter used by connected clients.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A controller method has no @Authenticated() metadata | The global guard rejects the route setup instead of silently treating it as public | Declare the route's public, user, admin, shared-link, and permission needs explicitly |
| A controller keeps a legacy path without its replacement or version history | Clients can use a path that is missing from the documented migration contract | Keep deprecated and hidden compatibility routes tied to the current operation |
| An account or administration route loses its permission or admin requirement | A user can receive data or perform an action outside the intended access scope | Keep @Authenticated() metadata aligned with the account, API-key, library, and user-admin contract |
| An API key is rotated while a client still uses the old secret | Requests made with the old secret fail immediately | Treat rotation as an invalidation event and update the client credential before retrying |
| A library scan or workflow action is exposed as a normal read operation | A request can appear successful without the server starting the intended work | Keep action routes separate from read routes and preserve their action permission |
| Request or response data fails its Zod schema | The client receives a validation error and the controller contract is not completed | Keep DTO schemas and shared validation rules aligned with client payloads |
| A people update contains no permitted field or a shared list contains duplicate IDs | The request is rejected before the service changes person access or data | Preserve the DTO refinements and uniqueness rules for people operations |
| A person merge client calls the deprecated path after the replacement is removed | The client cannot use the older merge contract during migration | Keep the deprecated path mapped to the current bulk merge behavior until its compatibility window ends |
| The API receives a browser request that does not accept HTML | The SSR path returns a not-acceptable response | Request JSON or another API response type for API paths |
| An upload is empty, rejected, or disconnected | The upload does not become a usable asset and a partial write may need cleanup | Use the upload boundary and asset service rather than writing files in a controller |
| A non-restart worker exits with a failure code | The supervisor stops the API and exits the application | Treat worker health as a single runtime contract and inspect the failed worker first |
| Maintenance mode is active or its database lock is held | Normal workers do not start until maintenance is complete | Clear maintenance state and release the database advisory lock before normal startup |
Key files
| File | Why to read it |
|---|---|
| server/…/main.ts | Explains worker supervision, maintenance mode, restart, and failure behavior |
| server/…/app.module.ts | Shows how API controllers, shared services, queues, telemetry, guards, pipes, and interceptors are composed |
| server/…/api.ts | Shows the API worker entry point and Nest application creation |
| server/…/app.common.ts | Defines the HTTP server boundary, global prefix, middleware, Swagger, static assets, SSR, and listener setup |
| server/…/index.ts | Maps the product route domains into the API module |
| server/…/auth.guard.ts | Defines the route authentication and authorization contract |
| server/…/validation.ts | Defines shared input rules used by API DTOs |
| server/…/global-exception.filter.ts | Defines the client-visible error and validation response shape |
| server/…/file-upload.interceptor.ts | Defines the multipart upload boundary and storage handoff |
| server/…/api.service.ts | Explains browser SSR and shared-link page metadata |
| server/…/websocket.adapter.ts | Explains Redis-backed real-time event delivery |
| server/…/server.controller.ts | Illustrates public, permission-protected, admin, and deprecated endpoint contracts |
| server/…/person.controller.ts | Illustrates scoped people operations, bulk actions, file responses, access management, and compatibility routes |
| server/…/user.controller.ts | Illustrates current-user, preference, onboarding, license, and profile-image contracts |
| server/…/workflow.controller.ts | Illustrates authenticated workflow operations and the public trigger contract |
| server/…/person.controller.spec.ts | Shows the client-visible validation and status guarantees for a representative controller |