Loading...
Ababil Hossain
Ababil Hossain

Programmer | DevTools & Open Source

A Modular TypeScript Backend Architecture: APIs, Business Logic, and Server-Rendered UI

A Modular TypeScript Backend Architecture: APIs, Business Logic, and Server-Rendered UI

A reusable TypeScript backend structure for module anatomy, data layer, shared plumbing, and request flow.

Most full-stack TypeScript projects start with the same question: should the frontend be a separate application, or should the server render the pages itself? Both answers are valid, but server rendering gets dismissed as old-fashioned even when it fits perfectly.

This article walks through a structure for a single server-rendered TypeScript application that also exposes a JSON API. Think of it as a reusable blueprint—boundaries, module anatomy, shared plumbing, and request flow. Nothing here locks you into a specific domain. Use it for a catalog, an internal dashboard, a marketplace, or a content site.

The goal is straightforward: keep HTTP handling out of business logic, keep database models out of route files, and give every new feature an obvious home.

The Core Idea

Everything below follows from five rules:

  • Split by interface, not technology.apis/returns JSON,ui/returns HTML, and both call the same services.
  • One module shape everywhere. A feature is a router, a controller, a service, and a validation schema; add an interface file when it owns a shape.
  • Controllers translate, services decide. Controllers turn HTTP into service calls; services hold the logic and never seereqorres.
  • Plumbing is shared. Validate at the route, map errors in one handler, format responses with one helper.
  • Build what development reads. The build output mirrors the source layout, so template and static paths never change between environments.

What follows is the detail behind those five rules, with code for each decision. Read it as a reference and take what you need.

The Problem: One Server, Two Kinds of HTTP

A server-rendered application usually ends up with two interfaces, whether you plan for it or not:

  • HTML requests for pages—the initial render, forms, and navigations.
  • JSON requests for behavior that shouldn’t reload the page—filtering, pagination, autocomplete, counters, background actions.

The common failure mode is mixing them. A controller renders a page but also returns JSON when a query flag is present. A template calls a service directly. A route file grows pagination math and response formatting. After a few months, nobody can tell where validation happens or which layer owns a database query.

The alternative is treating the two interfaces as separate route trees inside one application:

TEXT
/api/*   → JSON only
/*       → HTML only

That single split becomes the backbone of everything below. Each directory can then be classified by which tree it serves, or whether it serves both.

This structure fits when:

  • Your application is read-heavy and mostly renders the same data for everyone.
  • You want finished HTML on first paint, without a client bundle or hydration step.
  • One deployment, one set of environment variables, and one process is an advantage.
  • Your interactive UI is modest—a player, filters, modals, inline forms.

It’s a poor fit when the interface is a highly stateful client application, when offline support matters, or when multiple teams need to ship frontends independently.

The Stack and Why Each Piece Is There

Tool Role Why it belongs here
TypeScript Language Shared types across models, services, controllers, and view-data preparation
Express HTTP server and routing Explicit route trees, minimal abstraction, easy to audit
MongoDB + Mongoose Persistence Flexible documents, array fields, atomic counters, schema-level hooks
EJS Server-side rendering HTML with real data on first paint, no hydration
Vite + Tailwind CSS Stylesheet pipeline Compiles the stylesheet entry used by the templates
Zod Input validation Typed schemas that run at the edge and fail with readable messages
A bundler (Bun/esbuild) Server build One deployable file, TypeScript resolved, dependencies left external

Two details are worth calling out because they are often misunderstood.

In this setup, Vite isn’t building a frontend app. It compiles a single stylesheet entry through PostCSS and writes the result to a static directory. No client-side bundle is required because pages arrive as finished HTML. Browser behavior lives in small inline scripts included by templates.

The bundler is a deployment detail, not a framework. The server gets bundled to a single CommonJS file with dependencies left external, so the runtime only needsnode_modulesand the bundle. Development runs the TypeScript entry directly through a watcher, so you’re not rebuilding on every save.

The examples assume Express 5. That version forwards rejected promises fromasynchandlers automatically, which changes how much error plumbing you need. More on that below.

The Folder Map

Here’s the structure without domain-specific details:

TEXT
src/
├── server.ts            # process entry: config check, DB connection, HTTP server, shutdown
├── app.ts               # Express wiring: middleware, route mounting, 404
├── apis/
│   ├── router.ts        # mounts each API module under its path
│   └── items/           # router, controller, service, validation, interface
├── data/
│   ├── interfaces/      # plain TypeScript shapes
│   ├── models/          # Mongoose schemas and models
│   └── index.ts         # single barrel export
├── ui/
│   ├── router.ts        # HTML route table
│   ├── pages/           # public pages, each a module
│   ├── admin/           # authenticated pages and their router
│   ├── layouts/         # EJS layout shells
│   ├── partials/        # header, footer, shared widgets
│   ├── scripts/         # small browser scripts included by layouts
│   └── style.css        # Vite entry point for Tailwind CSS
├── middlewares/         # locals, validation, error handler
├── helpers/             # AppError, catchAsync, sendResponse
├── shared/              # integrations and adapters with no HTTP knowledge
├── utils/               # pure functions: formatting, pagination, renderWithLayout
├── config/              # environment schema and database connection
└── constants/           # HTTP codes, site config, base URL resolution
scripts/
├── app.sh               # Main build/dev/start orchestrator
└── setup.js             # File copying and Bun build script
vite.config.mjs          # Vite configuration for stylesheet compilation
tsconfig.json            # TypeScript compiler options and path aliases

The rule for deciding where a file goes is: a directory should be explainable in one sentence.

  • apishandles JSON over HTTP.
  • uihandles HTML over HTTP.
  • dataknows about the database and nothing about HTTP.
  • helpers,utils, andsharedknow about neither.

That last rule keeps the structure honest. When a function needs aRequestobject, it belongs in a controller. When it needs a database model, it belongs in a service or the data layer. When it only needs inputs and outputs, it belongs inutils.

The layout renderer sits underuirather thanutilsfor exactly that reason—it exists entirely to produce HTML responses. Treating it as a generic utility would blur the boundary the folder map is meant to protect.

Two Request Lifecycles

The clearest way to see the structure is to follow a request through each tree.

graph TD
    REQ[Incoming request] --> APP["app.ts middleware"]
    APP --> P{Path starts with /api?}
    P -->|Yes| API[apis/router.ts]
    API --> AR[module router]
    AR --> VAL["validate(schema, part)"]
    VAL --> AC["controller: read validated input + call service"]
    AC --> AS["service: query + transform"]
    AS --> DB[(Database)]
    AC --> RESP["sendResponse: JSON envelope"]
    P -->|No| UI[ui/router.ts]
    UI --> AUTH["optional auth guard"]
    AUTH --> UQ["validate(query schema)"]
    UQ --> UC[page controller]
    UC --> US[page service]
    US --> DB
    UC --> RW[renderWithLayout]
    RW --> TPL["page.ejs → layout.ejs"]
    TPL --> HTML[HTML response]
    AC -. "next(err)" .-> ERR[global error handler]
    UC -. "next(err)" .-> ERR
    RW -. "rejects" .-> ERR
    ERR --> JSON["JSON error for /api"]
    ERR --> PAGE["error page for HTML"]

    style REQ fill:#1e293b,stroke:#58a6ff,stroke-width:3px,color:#e6edf3
    style DB fill:#0d1117,stroke:#3fb950,stroke-width:3px,color:#e6edf3
    style RESP fill:#0d1117,stroke:#58a6ff,stroke-width:2px,color:#e6edf3
    style HTML fill:#0d1117,stroke:#3fb950,stroke-width:2px,color:#e6edf3
    style ERR fill:#0d1117,stroke:#ff6b6b,stroke-width:2px,color:#e6edf3
    style APP fill:#161b22,stroke:#8b949e,color:#e6edf3
    style API fill:#161b22,stroke:#8b949e,color:#e6edf3
    style UI fill:#161b22,stroke:#8b949e,color:#e6edf3

An API request forGET /api/items?search=report&page=2passes through global middleware, mounts under/api, hits the items router, and is validated againstListItemsQuerySchema. The controller receivessearch,page: 2, andperPage: 20—already coerced—calls the service, and sends the envelope. Nothing in that path renders HTML, and no controller parses a query string.

A page request forGET /?page=2reaches the UI router, passes the same validation step with that page’s schema, then the home controller and page service. The returned data goes intorenderWithLayout, which renderspages/home/page.ejsinto a string and injects it into the main layout. The layout adds metadata, stylesheets, navigation, and scripts.

The Build Pipeline

Keep the scripts thin and let them delegate to one shell file so development, build, and production can’t drift. Thepackage.jsondelegates to a shell script that handles each mode:

JSON
{
  "name": "your-app",
  "version": "1.0.0",
  "main": "./build/server.js",
  "type": "commonjs",
  "scripts": {
    "build": "sh scripts/app.sh build",
    "dev": "sh scripts/app.sh dev",
    "start": "sh scripts/app.sh start",
    "preview": "sh scripts/app.sh preview"
  }
}
BASH
# scripts/app.sh
#!/bin/bash
CONDITION=$1
case $CONDITION in
"build")
  vite build
  bun ./scripts/setup.js build
  ;;
"dev")
  bun ./scripts/setup.js sync
  NODE_ENV=development tsx --watch ./src/server.ts
  ;;
"start")
  sh scripts/app.sh build
  NODE_ENV=production bun ./build/server.js
  ;;
"preview")
  sh scripts/app.sh build
  NODE_ENV=preview bun ./build/server.js
  ;;
*)
  echo "Usage: sh scripts/app.sh [build|dev|start|preview]"
  ;;
esac

The mapping:

Script What it does
dev Syncs templates and static assets into the build directory, then watches TypeScript
build Compiles the stylesheet, bundles the server, copies templates and assets
start Builds, then runs the bundle withNODE_ENV=production
preview Builds, then runs the bundle with a preview environment

The build has two jobs that are easy to mix up:

  1. Bundle the server. One entry file, TypeScript resolved, path aliases honored, dependencies left external unless a specific package must be embedded for the host.
  2. Copy runtime files. Static assets go topublic/, and only.ejsand.cssfiles from the UI tree go toui/. Controllers and services never ship as separate files because they are already inside the bundle.

Neither job happens automatically. Vite builds the stylesheet from one entry defined in its config, and Bun bundles the server from explicit options:

JS
// vite.config.mjs
import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/postcss";

export default defineConfig({
  publicDir: false,
  css: {
    postcss: {
      plugins: [tailwindcss],
    },
  },
  build: {
    outDir: "public/css",
    emptyOutDir: false,
    rollupOptions: {
      input: "src/ui/style.css",
      output: {
        assetFileNames: "style.css",
      },
    },
  },
});
JS
// scripts/setup.js (excerpt - build function)
async function build() {
  try {
    if (fs.existsSync(outdir)) {
      fs.rmSync(outdir, { recursive: true, force: true });
    }
    fs.mkdirSync(outdir, { recursive: true });

    console.log("Building with Bun...");
    const result = await Bun.build({
      entrypoints: ["./src/server.ts"],
      outdir: "./build",
      target: "node",
      format: "cjs",
      sourcemap: "external",
      minify: false,
      external,
    });

    if (!result.success) {
      console.error("Build failed:");
      result.logs.forEach((log) => console.error(log));
      process.exit(1);
    }

    copyPublicFolder();
    copyViewsFolder();

    const size = (fs.statSync("./build/server.js").size / 1024).toFixed(2);
    console.log(`✓ Build successful!`);
    console.log(`  Bundle size: ${size} KB`);
  } catch (error) {
    console.error("Build failed:", error.message || error);
    process.exit(1);
  }
}

The copy step is written by hand in the same script because neither Vite nor Bun knows which non-TypeScript files the server reads at runtime: copypublic/recursively, and copy the.ejsand.cssfiles undersrc/ui/, preserving their relative paths. Showing the copy as a separate step is also a useful reminder that it can silently drift—a new asset directory that no script copies works in development and 404s in production.

Only after those steps does pointingviewsand the static middleware at thebuildpaths in every environment work. Development mirrors production from the filesystem’s point of view becausedevruns the same sync step before starting the watcher.

TypeScript configuration supports that:

JSON
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "Node16",
    "moduleResolution": "node16",
    "rootDir": "./src",
    "paths": {
      "@/*": ["./src/*"]
    },
    "outDir": "./build",
    "noEmitOnError": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules", "build", "temp"]
}

Alias resolution is bundler configuration, not a language feature: Bun readspathsfromtsconfig.jsonwhen bundling, while esbuild needs the tsconfig passed explicitly (or a resolver plugin) or@/datawill fail to resolve in the bundle even thoughtscaccepts it.

Shared Plumbing

Four small pieces remove repeated error handling from every module.

A typed application error carries an HTTP status with the message:

TS
export class AppError extends Error {
  constructor(
    public status: number,
    message: string,
    stack?: string,
  ) {
    super(message);
    this.name = "AppError";
    if (stack) {
      this.stack = stack;
    } else {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

An async wrapper forwards rejected promises to Express. It also has to catch synchronous throws, which a naivePromise.resolve(fn(...))doesn’t, becausefnis called before the promise exists:

TS
import type { RequestHandler } from "express";

export const catchAsync = (fn: RequestHandler): RequestHandler => {
  return (req, res, next) => {
    Promise.resolve()
      .then(() => fn(req, res, next))
      .catch(next);
  };
};

On Express 5 this wrapper is optional forasynchandlers, since a rejected promise is forwarded for you. It still has value: it makes the behavior explicit, it keeps the code portable to Express 4, and it covers handlers that mix synchronous throws with awaited calls. If you rely on native Express 5 handling instead, that’s a defensible choice—just choose one and don’t half-apply it.

A response helper enforces one JSON envelope—status,success,message,meta,data—so clients parse every JSON endpoint the same way:

TS
export const sendResponse = <T>(res: Response, info: TResponse<T>): void => {
  res.status(info.status).json({
    status: info.status,
    success: info.success,
    message: info.message,
    meta: info.meta,
    data: info.data,
  });
};

A global error handler is the single place that decides what an error looks like. Map known failure modes to statuses:

Condition Status Message in production
Database connection failure or timeout 503 Service temporarily unavailable
Duplicate key (err.code === 11000) 409 Resource already exists
Cast/parse failure 400 Invalid identifier format
Schema validation failure 400 Validation failed
AppError custom The error’s own message
Any otherError 500 Internal server error

Then branch on the path: requests under/apiget JSON (with a stack trace only in development), and everything else renders an error page through the public layout. A bad URL or a failed query should look like part of the site, not a bare stack trace.

Two guards belong first in that handler: checkres.headersSentandres.destroyed.

Once a streamed response has started, the status line is already on the wire, so the only safe action is to destroy the connection rather than attempt to send JSON or an error page. A client that disconnects early is the subtler case: the socket can be gone whileheadersSentis stillfalse, because nothing was ever written. Rendering a page or callingres.jsonthere writes into a closed connection and can surface a second error from the handler that was meant to report the first.

TS
if (res.headersSent || res.destroyed) {
  return req.socket.destroy();
}

Input validation

A thin Express middleware turns any Zod schema into a400with readable messages. It takes the request part as an argument, so the same helper validates bodies, query strings, and route parameters:

TS
// src/middlewares/validate.ts
import { ZodError, type z } from "zod";
import type { RequestHandler } from "express";
import * as helpers from "@/helpers";
import * as constants from "@/constants";

type RequestPart = "body" | "query" | "params";

const toValidationError = (error: ZodError): helpers.AppError =>
  new helpers.AppError(
    constants.HTTP_CODE.BAD_REQUEST,
    error.issues.map((issue) => issue.message).join(", "),
  );

export const validate = <T>(
  schema: z.ZodType<T>,
  part: RequestPart,
): RequestHandler => {
  return (req, res, next) => {
    schema
      .safeParseAsync(req[part])
      .then((result) => {
        if (!result.success) {
          return next(toValidationError(result.error));
        }

        res.locals.validated = {
          ...(res.locals.validated as Record<string, unknown>),
          [part]: result.data,
        };
        res.locals[part] = result.data;

        next();
      })
      .catch(next);
  };
};

The parsed value is stored underres.locals[part], so a query schema’s output is available asres.locals.queryand a body schema’s output asres.locals.body. Because the parsed object has coercions and defaults applied, the controller never sees the raw string from the URL.

The handler itself is synchronous: it starts the parse and returns a chained promise, so it behaves the same on Express 4 and Express 5. That matters because anasyncmiddleware whose promise is never attached to Express escapes the error handler on Express 4 whenever a custom refinement throws. The trailing.catch(next)covers exactly that case.

safeParseAsyncis used instead oftry/catchbecause it returns a discriminated result, which keeps the success path flat. The promise chain handles the rejection path. If every schema you write uses synchronous refinements only,safeParsewith atry/catchis equivalent and slightly cheaper.

The value is consistency: parsing, coercion, and error formatting happen before the controller runs, so controllers can trust their inputs. The schemas themselves stay in the module that owns the endpoint, which is whyapis/items/validation.tsandui/pages/home/validation.tsboth exist rather than one global schema file.

Optional middleware worth understanding

  • An HTML minifier can wrapres.sendand run templates throughhtml-minifier-terser, collapsing whitespace and minifying inline JS and CSS. It’s convenient, but because it replacesres.send, it processes every string body, not just HTML. Minifying inside the layout renderer instead keeps the behavior visible at the point where HTML is produced.
  • A static cache-header middleware can set longCache-Controlvalues for a small allowlist of large assets beforeexpress.staticruns. Wholesale long caching of every static path is how stale assets survive deployments.

The Data Layer Stands Alone

Splitdatainto pure interfaces and Mongoose schemas, then re-export both from one barrel:

TS
// src/data/index.ts
export * from "./interfaces/item.interface";
export * from "./models/item.model";
TS
// src/data/interfaces/item.interface.ts
import { Document } from "mongoose";

export interface IItem {
  title: string;
  status: "draft" | "published" | "archived";
  tags: string[];
  createdAt: Date;
  updatedAt: Date;
}

export interface IItemDocument extends IItem, Document {}
TS
// src/data/models/item.model.ts
import mongoose from "mongoose";
import type { IItemDocument } from "../interfaces/item.interface";

const itemSchema = new mongoose.Schema<IItemDocument>(
  {
    title: { type: String, required: true, trim: true },
    status: {
      type: String,
      enum: ["draft", "published", "archived"],
      default: "draft",
      index: true,
    },
    tags: { type: [String], default: [] },
  },
  { timestamps: true },
);

itemSchema.index({ createdAt: -1 });

export const Item = mongoose.model<IItemDocument>("Item", itemSchema);

The model imports its interface from the file that defines it, not from the barrel that re-exports the model.import typeerases at runtime, so either form works, but the direct path avoids a file that appears to depend on itself.

The split has a concrete benefit: a UI service can describe the view data it needs without importing Mongoose. Plain interfaces are cheap to import, easy to test against, and safe to share with any code that shouldn’t know about the database.

Keep the models outsideapisfor the same reason. Both the JSON services and the page services read the same collections. If a model lived inside one feature module, every other feature would import across a boundary or duplicate the schema.

Domain hooks belong in the model when they protect an invariant, not when they perform a workflow. Generating a public identifier, normalizing a field, or enforcing a lifecycle transition is reasonable. Sending an email from a Mongoose hook isn’t—that belongs in a service where the side effect is visible.

Anatomy of an API Module

Every API feature follows the same small set of files:

TEXT
apis/items/
├── router.ts       # paths, HTTP methods, and the validation each route requires
├── controller.ts   # reads validated input, calls the service, sends the response
├── service.ts      # querying, filtering, transforming
├── validation.ts   # Zod schemas plus the types inferred from them
└── interface.ts    # request, response, and query shapes

The router only wires paths to handlers and declares what each route accepts:

TS
// src/apis/items/router.ts
import { Router } from "express";
import { validate } from "@/middlewares";
import * as controller from "./controller";
import * as validation from "./validation";

const router = Router();

router.get(
  "/",
  validate(validation.ListItemsQuerySchema, "query"),
  controller.listItems,
);
router.get("/:id", controller.getItem);
router.post(
  "/",
  validate(validation.CreateItemSchema, "body"),
  controller.createItem,
);

export default router;

Both schemas live in the module’svalidation.tsand both are attached to routes, so there’s exactly one definition of “a valid request” per endpoint.validateis shown in the Shared Plumbing section.

The controller does three things and stops: read the already-validated input, call the service, send a response.

TS
// src/apis/items/controller.ts
import * as helpers from "@/helpers";
import * as constants from "@/constants";
import * as itemService from "./service";
import type { ListItemsQuery } from "./validation";

export const listItems = helpers.catchAsync(async (req, res) => {
  // The router has already parsed and coerced these values.
  const { search, page, perPage } = res.locals.query as ListItemsQuery;

  helpers.sendResponse(res, {
    success: true,
    status: constants.HTTP_CODE.OK,
    message: "Items retrieved successfully",
    data: await itemService.listItems({ search, page, perPage }),
  });
});

NoparseInt, no database call, no pagination math, no response formatting. The single assertion is safe because the route guarantees the shape, and the type comes fromz.infer, so it can’t drift from the schema.

The service owns the query and returns a plain object:

TS
// src/apis/items/service.ts
import * as data from "@/data";
import type * as interfaces from "./interface";

const escapeRegex = (value: string) =>
  value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

function toItemResponse(item: data.IItemDocument): interfaces.IItemResponse {
  return {
    id: String(item._id),
    title: item.title,
    status: item.status,
    createdAt: item.createdAt.toISOString(),
  };
}

export async function listItems({
  search,
  page,
  perPage,
}: interfaces.IListItemsInput): Promise<interfaces.IListItemsResult> {
  const filter = search
    ? { title: { $regex: escapeRegex(search), $options: "i" } }
    : {};

  const [items, total] = await Promise.all([
    data.Item.find(filter)
      .sort({ createdAt: -1 })
      .skip((page - 1) * perPage)
      .limit(perPage)
      .lean(),
    data.Item.countDocuments(filter),
  ]);

  return {
    total,
    page,
    perPage,
    totalPages: Math.ceil(total / perPage),
    items: items.map(toItemResponse),
  };
}

The module’s public types stay explicit as well, so a reader can see the contract without opening the schema or the service:

TS
// src/apis/items/interface.ts
export interface IItemResponse {
  id: string;
  title: string;
  status: "draft" | "published" | "archived";
  createdAt: string;
}

export interface IListItemsInput {
  search: string;
  page: number;
  perPage: number;
}

export interface IListItemsResult {
  total: number;
  page: number;
  perPage: number;
  totalPages: number;
  items: IItemResponse[];
}

Two properties make this worth the extra files:

  1. The controller is replaceable at the HTTP boundary. If you later switch from Express to another HTTP layer, controllers change and services don’t.
  2. The response shape is explicit. Returning plain objects means Mongoose documents never leak into a response, so fields like_id,__v, and internal notes aren’t accidentally exposed, and renaming a database field doesn’t silently break a public contract.

Zod schemas stay next to the module that uses them, and coercion is the part worth getting right:

TS
// src/apis/items/validation.ts
import { z } from "zod";

export const ListItemsQuerySchema = z.object({
  search: z.string().trim().max(100).default(""),
  page: z.coerce.number().int().min(1).default(1),
  perPage: z.coerce.number().int().min(1).max(100).default(20),
});

export const CreateItemSchema = z.object({
  title: z.string().trim().min(1).max(200),
  status: z.enum(["draft", "published", "archived"]).default("draft"),
  tags: z.array(z.string().trim().min(1)).max(10).default([]),
});

export type ListItemsQuery = z.infer<typeof ListItemsQuerySchema>;
export type CreateItemBody = z.infer<typeof CreateItemSchema>;

z.coerce.number()turns the string"2"into2, defaults fill in missing parameters, and a non-numeric value likepage=abcfails validation with a400instead of arriving at the service asNaN.

The practical risk in this pattern is defining schemas and then not attaching them. If a controller parses query strings by hand while a schema sits unused beside it, validation has two sources of truth. The router above attaches both schemas—the decay starts when a new route skips that step.

Where the boundary can be looser

In a strict reading, services shouldn’t import models either—a repository layer would sit between them. For small applications, that layer usually just forwards calls to Mongoose and adds indirection without adding a decision. The boundary that pays off is HTTP handling versus business logic, and that one is cheap to keep: nothing inservice.tstouchesreqorres.

If you expect to swap the database, or if multiple services query the same collection differently, add the repository. Otherwise, keep the service as the database boundary and document that choice.

Server-Rendered UI as a First-Class Layer

Theuidirectory mirrors the API module shape, withpage.ejsin place ofrouter.ts:

TEXT
ui/pages/home/
├── controller.ts   # reads validated input, calls the service, renders
├── service.ts      # builds the exact data the page needs
├── validation.ts   # query schema for filtering and pagination
├── interface.ts    # shape of that page data
└── page.ejs        # markup for the page body

Pages validate their query strings with the same middleware the API uses, so?page=abcfails before any database call:

TS
// src/ui/pages/home/validation.ts
import { z } from "zod";

export const HomeQuerySchema = z.object({
  search: z.string().trim().max(100).default(""),
  page: z.coerce.number().int().min(1).default(1),
});

export type HomeQuery = z.infer<typeof HomeQuerySchema>;
TS
// src/ui/pages/home/controller.ts
import * as helpers from "@/helpers";
import * as utils from "@/utils";
import * as homeService from "./service";
import type { HomeQuery } from "./validation";

export const renderHome = helpers.catchAsync(async (req, res) => {
  const { search, page } = res.locals.query as HomeQuery;
  const data = await homeService.prepareHomePageData({ search, page });

  utils.renderWithLayout(res, "pages/home/page", data);
});

The route that mounts it reads the same as the API route, with one difference: an invalid query renders an error page rather than a JSON body, because the global error handler branches on the path.

TS
// src/ui/router.ts (excerpt)
import { validate } from "@/middlewares";
import * as homeController from "./pages/home/controller";
import * as homeValidation from "./pages/home/validation";

router.get(
  "/",
  validate(homeValidation.HomeQuerySchema, "query"),
  homeController.renderHome,
);

The page service returns one predictable object containing everything the template needs. Templates receive data—they don’t query the database, and they don’t reach into globals.

Layouts, partials, and a small renderer

EJS has no built-in layout inheritance, so a helper renders the page body first and passes it into a layout asbody. It’s placed inutilssince it’s a pure rendering utility:

TS
// src/utils/render-with-layout.ts
import type { Response } from "express";

export interface RenderLayoutOptions {
  layout?: string | false;
  title?: string;
  [key: string]: any;
}

export function renderWithLayout(
  res: Response,
  view: string,
  options: RenderLayoutOptions = {},
): void {
  const layout =
    options.layout !== undefined ? options.layout : "layouts/main.layout.ejs";

  if (layout === false) {
    return res.render(view, options);
  }

  const layoutView =
    typeof layout === "string" && !layout.endsWith(".ejs")
      ? `${layout}.ejs`
      : layout;

  res.render(view, options, (err, html) => {
    if (err) {
      if (res.req && (res.req as any).next) {
        return (res.req as any).next(err);
      }
      return res.status(500).send(err.message);
    }

    res.render(layoutView as string, {
      ...options,
      body: html,
    });
  });
}

Both renders happen through callbacks, so a missing template in the page or in the layout reaches the error handler through the callback mechanism. The renderer checks for anextfunction on the request object to properly forward errors, falling back to a direct 500 response if needed.

Because the layout is chosen per call, the same structure supports several shells: a public layout, a wider admin layout, a stripped authentication layout, and a page that opts out withlayout: false.

Everything reused across pages lives inui/partials—header, footer, form controls, modals, toasts. Browser behavior lives inui/scriptsas small scripts included by the layout. That’s a deliberate trade: one stylesheet build and one server bundle instead of a client application, at the cost of writing plain DOM code rather than components.

Values every template expects

Instead of passing site metadata into everyrendercall, attach it once per request:

TS
// src/middlewares/locals.ts
import type { RequestHandler } from "express";
import * as config from "@/config";
import * as constants from "@/constants";

const addLocals: RequestHandler = (req, res, next) => {
  res.locals.config = {
    site: constants.SITE_CONFIG,
    env: {
      NODE_ENV: config.ENV.NODE_ENV,
      IS_DEV: config.ENV.NODE_ENV === "development",
    },
  };

  res.locals.currentYear = new Date().getFullYear();
  res.locals.canonicalPath = req.path;
  res.locals.absoluteUrl = (path = "") =>
    new URL(path, constants.SITE_URL).toString();

  next();
};

export default addLocals;

Templates can now useabsoluteUrl('/img/logo.png')in Open Graph tags andconfig.site.titlein the footer without page-specific wiring.SITE_URLitself should be derived in one place from the environment, so absolute URL behavior never drifts between pages.

Validate that base URL at startup in the same environment schema that validates everything else, and let the helper assume it’s usable. Atry/catchhere that returns the raw path would turn a malformedSITE_URLinto plausible-looking output: wrong canonical links and broken Open Graph previews, with no error to point at the real cause. Failing at boot is the cheaper outcome.

Authenticated pages are just another module

The admin area follows the same controller–service–template pattern. What it adds is a router-level guard:

TS
router.get("/dashboard", checkAdminAuth, dashboardController.renderDashboard);
router.post("/items/create", checkAdminAuth, itemFormController.createItem);

A typical guard reads a signed token from anhttpOnly,sameSite: "strict"cookie and redirects to the login page on failure. HTML authentication differs from API authentication in the failure mode: a browser navigation redirects, while an API call returns401. Keeping both behaviors in middleware means page controllers never check sessions.

Those cookie flags reduce exposure but aren’t a CSRF strategy on their own.httpOnlykeeps scripts from reading the token, andsameSite: "strict"blocks most cross-site submissions, yet the protection depends on browser behavior, deployment details, and which requests count as same-site. APOST /items/createroute behind cookie auth is a state-changing endpoint, so it needs an explicit defense. The checklist at the end of the article covers the options. Don’t treat the cookie attributes as a substitute.

Trade-offs and When Not to Use This Structure

Every structural decision has a cost. These are the ones you should accept deliberately.

One application instead of a separate frontend. You get one deploy, one environment, one route table, and no client-side data fetching for the initial render. The cost is that interactive behavior is written as plain DOM scripts, every interaction is manual, and shared state across widgets needs discipline. For a read-heavy application, the trade is good. For a highly interactive app, it isn’t.

EJS instead of a component framework. Templates are one language, render finished HTML, and are easy to reason about. But partials are string includes: no component state, no prop validation, and template typos surface only at render time.

A document database instead of a relational one. Flexible documents and atomic$inccounters are convenient, and adding a field needs no migration. The cost appears in ad-hoc search and reporting. If your queries are relational, use a relational database. This structure works with either, and the service layer is where that choice stays contained.

Search in application code. A regex prefilter plus in-memory scoring (n-grams, edit distance, prefix matching) can handle typos that a basic text index misses. It doesn’t scale indefinitely. Past a certain catalog size, move ranking into a search index and keep the service interface unchanged.

Duplicated query logic between API and UI services. The API service returns JSON and the page service returns view data, so the pagination and filtering logic tends to be written twice. This is the most common decay in this structure. Extract the shared query into one module that both services call, and let each service shape the result for its consumer. Do it before the two copies drift.

A global response transform. An HTML minifier that patchesres.sendis invisible at the call site and applies to responses that aren’t HTML. Prefer minifying where the HTML is generated.

Validators that are defined but not used. As noted in the API section, a schema only helps when its route attaches it. Partial adoption is worse than none because it misleads the next reader into trusting an endpoint that was never validated.

What this structure does not solve

The folder map organizes code, not policy. A few concerns still need a deliberate answer elsewhere:

  • Authorization isn’t implied by authentication middleware. The guard shown earlier proves who the user is. Deciding whether they may edit a given item requires a check in the service or a policy module, keyed by the user and the resource, not by the route.
  • CSRF protection isn’t provided by cookie flags. The authenticatedPOSTshown earlier is state-changing, andhttpOnlyplussameSite: "strict"only reduce the attack surface. Add a per-session token in every form (and send it in a header for fetch calls), or enforce a strictOrigin/Sec-Fetch-Sitecheck in middleware. The structure has an obvious home for either, but it won’t appear on its own.
  • Transactions. A service that writes several documents can fail halfway. MongoDB needs a session and replica set for multi-document transactions, and the service layer is the only sensible place to open one.
  • Observability. Structured logs, request IDs, and latency metrics don’t appear because the code is organized. They need explicit instrumentation, ideally in middleware and in the error handler so failures are counted in one place.
  • Background and scheduled jobs are outside the request cycle entirely. They need their own entry point that reuses services, not controllers, which is another argument for keeping business logic free ofreqandres.

Conclusion

The architecture comes down to a handful of rules that are cheap to follow and keep a codebase navigable as it grows:

  • Split by interface, not by technology:apisfor JSON,uifor HTML.
  • Give every feature the same module shape, so a new endpoint or page has an obvious home.
  • Keep HTTP handling in controllers, business logic in services, and persistence indata.
  • Validate every input with a schema attached at the route, and let controllers read typed data.
  • Put error mapping, response formatting, and configuration in shared plumbing so no module repeats them.
  • Make the build output mirror development, so template paths and static paths behave the same everywhere.
  • Every shared abstraction must earn its place: add a repository or a generic base controller only when it removes a real decision, not to look architectural.

None of this is novel. It’s deliberate consistency: one pattern applied to every module, one place for errors, one place for configuration, and one boundary between JSON and HTML. That consistency is what makes the structure reusable. Adding a feature means copying a known shape instead of deciding where code belongs.

Additional Resources

Documentation

Architecture & Security

Join the conversation

Share your thoughts

Loading comments...
Reading Progress 0%

Share this post