# Understanding the Role of the src Directory in the Open-SEO Project Structure

> Discover the crucial role of the src directory in the Open-SEO project structure. It holds all application logic, including bootstrap code, server functions, utilities, types, and more.

- Repository: [Every App/open-seo](https://github.com/every-app/open-seo)
- Tags: internals
- Published: 2026-08-16

---

**The `src` directory in the `every-app/open-seo` repository serves as the single source of truth for all application logic, containing the TanStack React-Start bootstrap code, server functions, shared utilities, type definitions, database schema, and middleware that power the SEO platform.**

The `open-seo` project follows a layered architecture where every piece of business logic lives inside the `src` folder. This organization ensures type safety across client-server boundaries and enables the same codebase to support both hosted SaaS and self-hosted deployments. Understanding the role of the `src` directory is essential for navigating the TanStack Start-based architecture effectively.

## Core Components Inside the src Directory

The `src` folder is organized by technical responsibility rather than feature domains. Each subdirectory serves a specific architectural purpose, from handling HTTP requests to validating external API payloads.

### Server Functions (src/serverFunctions)

The `src/serverFunctions` directory implements the **TanStack server-function API** that the frontend calls for SEO-related operations. These functions handle rank tracking, keyword research, Lighthouse audits, and integrations with external services like Google Search Console.

Key files include [`rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/rank-tracking.ts) for SERP position monitoring and [`keywords.ts`](https://github.com/every-app/open-seo/blob/main/keywords.ts) for keyword research operations. According to the `open-seo` source code, these server functions are directly imported and called from React components using TanStack's `useServerFunction` hook.

### Shared Utilities (src/shared)

The `src/shared` directory contains **isomorphic code** used by both client and server contexts. This prevents duplication of logic that must run in both environments, such as JSON parsing helpers, colour palette generators, and billing verification checks.

Representative files include [`json.ts`](https://github.com/every-app/open-seo/blob/main/json.ts) for safe JSON parsing and [`billing.ts`](https://github.com/every-app/open-seo/blob/main/billing.ts) for subscription status validation. The shared utilities ensure that validation logic remains consistent whether checking permissions during server rendering or client-side form submission.

### Type Definitions (src/types)

The `src/types` directory houses **TypeScript type definitions** and Zod schemas that describe data shapes exchanged with external APIs and persisted in the database. This includes schemas for DataForSEO responses, Google Search Console data structures, and internal database entities.

Files like [`src/types/schemas/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/types/schemas/keywords.ts) define Zod schemas that validate keyword data (including fields like `volume`, `difficulty`, and `phrase`) before it enters the application flow, providing runtime type safety beyond compile-time checks.

### Database Layer (src/db)

The `src/db` directory contains the **Drizzle ORM** configuration, including schema definitions, migration helpers, and database client wrappers. This layer abstracts the underlying storage (supporting both SQLite/Postgres via D1 or traditional Postgres) from the application logic.

Key files include [`schema.ts`](https://github.com/every-app/open-seo/blob/main/schema.ts) for table definitions and [`provider.ts`](https://github.com/every-app/open-seo/blob/main/provider.ts) for the database client initialization. The provider exposes a `db` object used throughout the server functions for querying projects, keywords, and audit results.

### Request Middleware (src/middleware)

The `src/middleware` directory implements **Express-like middleware** that runs before every server function call. This centralizes cross-cutting concerns like user authentication, CSRF protection, and global error handling.

Files such as [`ensureUser.ts`](https://github.com/every-app/open-seo/blob/main/ensureUser.ts) verify JWT tokens or session cookies before allowing access to protected resources, while [`errorHandling.ts`](https://github.com/every-app/open-seo/blob/main/errorHandling.ts) standardizes error responses across the API surface.

## Architecture Flow: How src Components Work Together

The `src` directory orchestrates the request lifecycle through a specific initialization sequence that wires together routing, middleware, and business logic.

**Entry Point Initialization**

The bootstrap process begins in [`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts), which creates the TanStack React-Start instance. This file registers global middleware including CSRF protection:

```typescript
// src/start.ts
import { createCsrfMiddleware, createStart } from "@tanstack/react-start";
import { globalServerFunctionMiddleware } from "@/serverFunctions/middleware";

const csrfMiddleware = createCsrfMiddleware({
  filter: (ctx) => ctx.handlerType === "serverFn",
});

export const startInstance = createStart(() => ({
  requestMiddleware: [csrfMiddleware],
  functionMiddleware: globalServerFunctionMiddleware,
}));

```

**Routing and Component Mapping**

The [`src/routeTree.gen.ts`](https://github.com/every-app/open-seo/blob/main/src/routeTree.gen.ts) file (auto-generated by TanStack Start) defines the client-side route tree that maps URLs to React components. This file connects the browser's address bar to the specific UI components rendered for each path.

**Request Handling Pipeline**

When a user interacts with the UI, the frontend calls server functions imported from `src/serverFunctions`. These functions first pass through the middleware chain defined in `src/middleware` (authentication and error handling), then execute business logic using utilities from `src/shared` and database access via `src/db`, with all data validated against schemas in `src/types`.

## Practical Code Examples from the Open-SEO src Directory

The following examples demonstrate how developers interact with the `src` directory contents in real implementations.

### Calling Server Functions from React Components

Server functions defined in `src/serverFunctions` are consumed directly by React components using TanStack's hooks:

```tsx
// Example React component
import { useServerFunction } from "@tanstack/react-start";
import { rankTracking } from "@/serverFunctions/rank-tracking";

export function RankTracker() {
  const { mutateAsync: fetchRank } = useServerFunction(rankTracking);

  const handleClick = async () => {
    const result = await fetchRank({ domain: "example.com", keyword: "open seo" });
    console.log(result);
  };

  return <button onClick={handleClick}>Check Rank</button>;
}

```

This pattern ensures type safety across the network boundary, as the `rankTracking` function's signature is shared between client and server via the `src/types` definitions.

### Using Shared Utilities for Data Parsing

The `src/shared` utilities provide safe abstractions for common operations like JSON parsing:

```typescript
import { safeParseJSON } from "@/shared/json";

const data = safeParseJSON('{"foo":"bar"}');
if (data) {
  console.log(data.foo); // "bar"
}

```

This helper prevents runtime crashes from malformed JSON while providing proper TypeScript inference for the parsed result.

### Defining Data Validation Schemas

External API responses are validated using Zod schemas defined in `src/types`:

```typescript
import { z } from "zod";

export const KeywordSchema = z.object({
  id: z.string(),
  phrase: z.string(),
  volume: z.number(),
  difficulty: z.number(),
});

```

These schemas ensure that data from services like DataForSEO conforms to expected shapes before being processed by the application logic.

### Querying the Database Layer

Server functions access the database through the provider defined in `src/db`:

```typescript
import { db } from "@/db/provider";

export async function getProject(id: string) {
  return await db.select().from(projects).where(eq(projects.id, id));
}

```

The `db` object abstracts the underlying Drizzle configuration, allowing the same code to run against local SQLite during development and Postgres in production.

## Summary

- The `src` directory contains **all application source code** for the `open-seo` project, organized by technical responsibility rather than feature domains.
- **`src/serverFunctions`** houses the TanStack server-function implementations for SEO operations like rank tracking and keyword research.
- **`src/shared`** provides isomorphic utilities (JSON helpers, billing logic) used by both client and server contexts.
- **`src/types`** defines Zod schemas and TypeScript interfaces that enforce data contracts with external APIs and the database.
- **`src/db`** contains Drizzle ORM configuration, schema definitions, and database client wrappers supporting multiple database backends.
- **`src/middleware`** implements request preprocessing logic including authentication, CSRF protection, and error handling.
- **[`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts)** bootstraps the TanStack React-Start instance with global middleware configuration.

## Frequently Asked Questions

### What types of operations are defined in src/serverFunctions?

The `src/serverFunctions` directory contains server-side implementations for SEO-specific workflows including rank tracking (monitoring keyword positions in search results), keyword research (analyzing search volume and difficulty), Lighthouse audits (performance scoring), and integrations with Google Search Console. These functions are called remotely from the React frontend while executing on the server.

### How does src/shared differ from src/types?

**`src/shared`** contains executable code and logic utilities (like JSON parsers or billing validators) that run in both browser and server environments, whereas **`src/types`** contains static TypeScript type definitions and Zod schemas used for compile-time type checking and runtime data validation. The shared utilities are imported and executed; the types are erased at runtime but power the Zod validation logic.

### What is the purpose of src/middleware in the request lifecycle?

The `src/middleware` directory contains functions that execute before server functions process requests, handling cross-cutting concerns like verifying user authentication via [`ensureUser.ts`](https://github.com/every-app/open-seo/blob/main/ensureUser.ts) and normalizing error responses via [`errorHandling.ts`](https://github.com/every-app/open-seo/blob/main/errorHandling.ts). This middleware layer ensures that every server function call undergoes consistent security and error-handling checks without duplicating code in individual function implementations.

### How does the src/db directory support different deployment environments?

The `src/db` directory abstracts database access through Drizzle ORM configuration in files like [`provider.ts`](https://github.com/every-app/open-seo/blob/main/provider.ts) and [`schema.ts`](https://github.com/every-app/open-seo/blob/main/schema.ts), allowing the same application code to run against SQLite (for local development or Cloudflare D1) or PostgreSQL (for production SaaS deployments). The provider pattern encapsulates connection logic, so server functions interact with a consistent `db` interface regardless of the underlying database engine.