LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
TypeScript

Project Structure for Frontend & Backend Apps

When a project starts small, putting all files into a couple of folders feels fast and easy. Six months later, that same codebase turns into a maze. Developers waste hours hunting for files, backend API changes silently break the frontend, and every pull request turns into an argument about spaces versus tabs.

Project Structure for Frontend & Backend Apps

When a project starts small, putting all files into a couple of folders feels fast and easy. Six months later, that same codebase turns into a maze. Developers waste hours hunting for files, backend API changes silently break the frontend, and every pull request turns into an argument about spaces versus tabs.

A clean project structure fixes these problems before they start. By using predictable folder conventions, sharing Data Transfer Objects (DTOs) and validation schemas, and enforcing strict linting and formatting rules, your frontend and backend teams can move fast without breaking each other's work.

What you will learn
  • How to organize a full-stack codebase using clean, feature-based folder conventions.
  • How to share DTOs and validation schemas between frontend and backend apps.
  • How to configure strict linting (ESLint) and formatting (Prettier) across the entire repo.
  • How data and types flow in a modern monorepo architecture.
  • Common structural mistakes and how to answer architecture questions in interviews.

1. Clean Folder Conventions: Feature-Based vs. Layer-Based

Most beginners organize code by file type (layer-based), putting all controllers in one folder and all components in another. As the app grows, changing a single feature like “Orders” forces you to jump between six different folders.

A feature-based structure groups files by business domain. Everything related to orders lives inside an orders/ folder, and everything related to users lives inside a users/ folder.

Approach How files are grouped Best for
Layer-based By technical role (controllers/, components/, services/) Very small apps or quick prototypes
Feature-based By business domain (features/orders/, features/auth/) Growing production apps and multi-developer teams

Keeping your frontend, backend, and shared types in one workspace (a monorepo) makes it easy to enforce one set of rules across the whole project.

Example 1: Clean monorepo folder tree

my-fullstack-app/
├── apps/
│   ├── web/                        # Frontend (React / Next.js)
│   │   ├── src/
│   │   │   ├── features/
│   │   │   │   └── orders/
│   │   │   │       ├── OrderForm.tsx
│   │   │   │       ├── useCreateOrder.ts
│   │   │   │       └── orderApi.ts
│   │   │   └── shared/             # Reusable UI buttons, layouts
│   │   └── package.json
│   └── api/                        # Backend (Node.js / Express or NestJS)
│       ├── src/
│       │   ├── modules/
│       │   │   └── orders/
│       │   │       ├── order.controller.ts
│       │   │       ├── order.service.ts
│       │   │       └── order.routes.ts
│       │   └── config/             # Env vars, database setup
│       └── package.json
├── packages/
│   └── shared/                     # Shared DTOs, Zod schemas, constants
│       ├── src/
│       │   ├── schemas/
│       │   │   └── order.schema.ts
│       │   └── index.ts
│       └── package.json
├── eslint.config.js                # One strict linting config for all apps
├── .prettierrc                     # One formatting config for all apps
└── package.json                    # Workspace root scripts
Note for .NET / Python Backends: If your backend is written in C# (.NET Core) or Python (FastAPI) and your frontend is React, you cannot directly import TypeScript files into C# or Python. Instead, generate an OpenAPI (Swagger) spec from your backend and use a tool like openapi-typescript to auto-generate the frontend DTOs automatically.

2. Shared DTOs and Schema Types

One of the most common bugs in full-stack apps happens when the backend renames a field (for example, changing totalPrice to totalAmount) and forgets to tell the frontend. The app compiles fine, deploys to production, and crashes for real users.

By defining your Data Transfer Objects (DTOs) and validation schemas in packages/shared using a library like Zod, both the frontend form and the backend API use the exact same contract.

Step 1: Define the Shared Schema

Example 2: packages/shared/src/schemas/order.schema.ts

import { z } from "zod";

export const CreateOrderSchema = z.object({
    customerId: z.string().uuid("Invalid customer ID"),
    items: z.array(
        z.object({
            productId: z.string().min(1),
            quantity: z.number().int().positive(),
        })
    ).min(1, "Order must have at least one item"),
});

// Automatically infer the TypeScript DTO type from the schema
export type CreateOrderDto = z.infer<typeof CreateOrderSchema>;

Step 2: Use It in Both Backend and Frontend

Example 3: Backend validation (apps/api/src/modules/orders/order.controller.ts)

import { Request, Response } from "express";
import { CreateOrderSchema, CreateOrderDto } from "@my-app/shared";

export function createOrder(req: Request, res: Response) {
    const parsed = CreateOrderSchema.safeParse(req.body);

    if (!parsed.success) {
        return res.status(400).json({ errors: parsed.error.flatten() });
    }

    const orderData: CreateOrderDto = parsed.data;
    return res.status(201).json({ status: "CREATED", data: orderData });
}

Example 4: Frontend API call (apps/web/src/features/orders/orderApi.ts)

import { CreateOrderDto } from "@my-app/shared";

export async function submitOrder(payload: CreateOrderDto) {
    const response = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
    });
    return response.json();
}

Expected output when invalid data is sent to the API

HTTP/1.1 400 Bad Request
{
  "errors": {
    "fieldErrors": {
      "items": ["Order must have at least one item"]
    }
  }
}

3. Architecture & Shared Contract Flow Visualized

Here is how a single shared package keeps your frontend, backend, and code quality tools synchronized in real time.

Full-Stack Monorepo: Shared Types & Quality Gate Flow

packages/shared Zod Schemas & TypeScript DTOs apps/web (Frontend) Forms & Typed API Client apps/api (Backend) Controllers & Request Validation Typed JSON Request Root Quality Gate (CI/CD) ESLint + Prettier + TypeScript Check

Both apps import the exact same DTO contract. Before any code is merged, the root quality gate checks linting, formatting, and type safety across all folders.

4. Strict Linting and Formatting Rules

Linting and formatting solve two different problems, and you need both:

  • Linter (ESLint): Catches logic bugs, unused variables, unsafe any types, and broken imports.
  • Formatter (Prettier): Automatically fixes indentation, quotes, semicolons, and line wrapping so every file looks like it was written by one person.

Example 5: Root formatting rules (.prettierrc)

{
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 100
}

Example 6: Root scripts in package.json

{
  "name": "my-fullstack-app",
  "private": true,
  "workspaces": ["apps/*", "packages/*"],
  "scripts": {
    "lint": "eslint . --max-warnings=0",
    "format:check": "prettier --check .",
    "typecheck": "tsc --noEmit",
    "check:all": "npm run lint && npm run format:check && npm run typecheck"
  }
}

Step-by-Step Enforcement Workflow

Step 1 (Editor): Enable “Format on Save” in VS Code so Prettier formats files automatically every time a developer hits Save.
Step 2 (Pre-Commit): Use Husky and lint-staged to run ESLint and Prettier only on changed files before a Git commit succeeds.
Step 3 (CI Pipeline): Run npm run check:all in GitHub Actions on every Pull Request. Notice --max-warnings=0—warnings are treated as errors so technical debt never piles up.
Watch out: Never rely on developers remembering to run the linter manually. If it is not enforced automatically in your CI/CD pipeline, the rules will be ignored within two weeks.

5. Hands-On Practice

Beginner Exercise 1: Refactor a Layer-Based Folder

Take a small app that has controllers/, services/, and models/ folders for Users and Products. Reorganize them into a feature-based modules/users/ and modules/products/ structure.

Hint: Keep truly global helpers (like database connection or logger) in a shared/ or core/ folder.

Intermediate Exercise 2: Create a Shared User Schema

Write a Zod schema called RegisterUserSchema with email (valid email format) and password (minimum 8 characters). Export both the schema and the inferred TypeScript type.

Expected result: Passing an invalid email to RegisterUserSchema.safeParse() returns success: false with a clear error message.

Advanced Exercise 3: Add a Strict CI Quality Gate

Add a root check:all script that runs ESLint with --max-warnings=0, Prettier check, and TypeScript compilation. Intentionally leave an unused variable in a file and verify that the script fails.

Hint: Use eslint-config-prettier so ESLint and Prettier never fight over formatting rules.

6. Interview Questions

Q1. Why do senior engineers prefer feature-based folder structures over layer-based ones?

Answer: Feature-based structures keep related code together (high cohesion). When you need to update or delete a feature, all its files live in one folder, making code navigation faster and reducing accidental side effects in other parts of the app.

Q2. What is the benefit of sharing DTOs and schemas between frontend and backend?

Answer: It creates a single source of truth. If the backend changes an API field name or data type, the frontend immediately fails at compile time during development rather than crashing silently in production.

Q3. How do you share types if your backend is in C# (.NET) or Python and your frontend is in React?

Answer: You use contract-first or schema-generation tools. Export an OpenAPI (Swagger) specification from the .NET or Python backend, and run a generator like openapi-typescript in your CI pipeline to automatically generate matching TypeScript DTOs for the frontend.

Q4. What is the difference between a linter and a formatter?

Answer: A linter (like ESLint) analyzes code quality and catches potential bugs, unused variables, and bad patterns. A formatter (like Prettier) only cares about visual style—indentation, quotes, and line breaks—so the codebase stays visually consistent.

Conclusion

A great project structure is invisible when it works well. Developers know exactly where to put new files, shared DTOs catch API mismatches before code is even committed, and strict linting eliminates pointless style debates during code reviews.

Start by organizing your next project around business features, centralize your data contracts, and automate your quality checks in CI. Your future self—and your entire engineering team—will thank you.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.