Backend Architecture (Inversify & Express)
Relevant source files
The following files were used as context for generating this wiki page:
The GoGovSG backend uses the Express web framework for request handling and InversifyJS for Dependency Injection (DI). This architecture decouples business logic from HTTP concerns, allowing services, controllers, and repositories to be injected as dependencies. The application serves three distinct environments—Go.gov.sg, for.edu.sg, and for.sg—using a shared codebase configured via environment variables.
Sources: src/server/index.ts:1-30, README.md:21-25
Core Application Bootstrap
The server initializes by configuring tracing, registering dependency injections, and setting up the Express application. The entry point is src/server/index.ts.
Initialization Sequence
- Tracing and Metadata: The application imports tracing utilities and
reflect-metadataat the top level. - Dependency Binding: The
bindInversifyDependencies()function executes before any module that requires injected containers. - Database and External Clients: The system initializes the PostgreSQL database and OIDC clients (if enabled).
- Middleware Pipeline: Express attaches standard and specific middleware (Helmet, Morgan, BodyParser, Sessions).
- Route Registration: The server mounts the
/apirouter and the redirect endpoint.
Sources: src/server/index.ts:1-40, src/server/index.ts:133-145, test/server/api/setup.ts:14-16
The diagram shows the synchronous startup flow required to ensure the Inversify container is ready before routes are loaded.
Sources: src/server/index.ts:1-210
Dependency Injection with InversifyJS
InversifyJS manages the lifecycle and instantiation of backend components. It uses a singleton container to store bindings between identifiers and implementations.
Container Configuration
The inversify.config.ts file maps DependencyIds to specific classes. This allows the application to swap implementations (e.g., using mocks during testing) without modifying the consuming code.
| Component Type | Examples |
|---|---|
| Controllers | UserController, RedirectController, BulkController |
| Services | Mailer, OneGovSgClient |
| Utilities | FileCheckController, UrlCheckController |
Sources: src/server/util/inversify.ts:1-5, src/server/api/user/index.ts:27-50, test/server/api/setup.ts:14-18
Component Relationship
The diagram illustrates how the central Container resolves dependencies using unique identifiers defined in the system.
Sources: src/server/util/inversify.ts, src/server/api/user/index.ts:27-32
Express Request Handling
The backend exposes a RESTful API under the /api prefix and handles shortlink redirects at the root level.
Middleware Implementation
The application uses different middleware stacks based on the route type to optimize performance and security.
- Global Middleware:
helmet(for CSP/security headers),morgan(for request logging), andcookieParser. - API Middleware:
express-sessionwith a Redis store, andbody-parserfor JSON payloads. - Redirect Middleware:
cookie-sessionfor tracking visits over a 1-week period.
Sources: src/server/index.ts:100-120, src/server/index.ts:165-195
User API Routes
The src/server/api/user/index.ts file defines endpoints for link management. It utilizes express-joi-validation for schema enforcement.
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/user/url | Creates a short URL or file link. |
| POST | /api/user/url/bulk | Bulk creates links via CSV upload. |
| PATCH | /api/user/url | Updates link metadata or replaces files. |
| GET | /api/user/url | Retrieves links owned by the authenticated user. |
Sources: src/server/api/user/index.ts:74-125
Request Flow for URL Creation
The sequence shows the multi-layered validation and threat checking performed before a link is persisted to the database.
Sources: src/server/api/user/index.ts:80-92
Infrastructure & Storage
GoGovSG relies on external services for persistence and transient state management.
- PostgreSQL: Stores short-to-long URL mappings, user accounts, and tags.
- Redis: Managed via multiple instances for:
REDIS_SESSION_URI: Session persistence.REDIS_OTP_URI: One-time password storage.REDIS_REDIRECT_URI: Caching frequently accessed shortlinks.REDIS_STAT_URI: Click statistics.
- AWS S3: Stores user-uploaded files and assets.
Sources: README.md:120-140, src/server/index.ts:168-175
Development and Testing Environment
The architecture supports local development through Docker Compose, which spins up the required database and Redis containers.
- Hot Reloading:
tsx watchmonitors server-side changes, while Webpack Dev Server handles frontend changes. - Mocking: In the testing environment,
bindInversifyDependenciesis called after mocks are registered in the container to ensure unit tests isolate logic from external services like Redis or the Mailer.
Sources: README.md:95-105, test/server/api/setup.ts:14-25
Summary
The GoGovSG backend architecture prioritizes security and maintainability through a clear separation of concerns. InversifyJS facilitates a highly testable system by managing component lifecycles, while Express provides a robust routing and middleware framework. This structure ensures that threat detection, validation, and business logic are consistently applied across all link management operations.