# What Is the Purpose of the src Directory in OpenSEO? A Complete Architecture Guide

> Discover the purpose of the src directory in OpenSEO. This guide explains how it houses all source code, organizing TanStack Start, server functions, utilities, and more in a layered architecture.

- Repository: [Every App/open-seo](https://github.com/every-app/open-seo)
- Tags: architecture
- Published: 2026-07-30

---

**The `src` directory serves as the monolithic container for all OpenSEO application source code, organizing the TanStack Start bootstrap, server functions, shared utilities, type definitions, database layer, and middleware into a clean, layered architecture.**

In the `every-app/open-seo` repository, the `src` folder represents the single source of truth for business logic and data handling. It implements a modular structure that separates concerns by responsibility—from API endpoints to database schemas—enabling both SaaS and self-hosted deployments to share identical code paths.

## Overview of the src Directory Structure

The `src` directory follows a domain-driven organization where each subfolder owns a specific technical responsibility. This structure prevents circular dependencies and ensures that client-side and server-side code can safely share common utilities without leaking implementation details. According to the repository's source code, the directory contains seven primary areas of concern: server functions, shared utilities, type definitions, database schemas, middleware, and application entry points.

## Core Subdirectories and Their Responsibilities

### serverFunctions: The TanStack Server-Function API

The `src/serverFunctions` directory implements TanStack's server-function mechanism, exposing typed remote procedures that the React frontend calls for SEO operations. These files handle rank tracking, keyword research, and Lighthouse audits.

For example, [`src/serverFunctions/rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/rank-tracking.ts) exports functions that the UI consumes directly:

```ts
// Example React component consuming a server function
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>;
}

```

*Source:* [`src/serverFunctions/rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/src/serverFunctions/rank-tracking.ts)

### shared: Cross-Cutting Utilities

The `src/shared` folder houses stateless utilities used by both client and server contexts. These helpers keep the codebase DRY (Don't Repeat Yourself) by centralizing common logic like JSON parsing, colour palette generation, and Google Search Console wrappers.

A typical usage pattern involves importing helpers directly into components or server functions:

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

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

```

*Source:* [`src/shared/json.ts`](https://github.com/every-app/open-seo/blob/main/src/shared/json.ts)

### types: Zod Schemas and TypeScript Definitions

Located in `src/types`, this directory contains TypeScript interfaces and Zod schemas that enforce data contracts with external APIs (DataForSEO, Google Search Console) and validate database inputs. The schemas ensure runtime type safety beyond compile-time checks.

For instance, keyword data structures are defined in [`src/types/schemas/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/types/schemas/keywords.ts):

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

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

```

*Source:* [`src/types/schemas/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/types/schemas/keywords.ts)

### db: Database Abstraction with Drizzle

The `src/db` directory encapsulates all database concerns using Drizzle ORM. It contains schema definitions in [`schema.ts`](https://github.com/every-app/open-seo/blob/main/schema.ts), migration utilities, and provider abstractions that allow the same codebase to run on SQLite (local development) or Postgres (production).

Database access occurs through the provider pattern:

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

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

```

*Source:* [`src/db/provider.ts`](https://github.com/every-app/open-seo/blob/main/src/db/provider.ts)

### middleware: Request Pre-Processing Pipeline

Files in `src/middleware` implement Express-like middleware that executes before every server function or HTTP request. This layer centralizes cross-cutting concerns like CSRF protection (`createCsrfMiddleware`), user authentication ([`ensureUser.ts`](https://github.com/every-app/open-seo/blob/main/ensureUser.ts)), and global error handling ([`errorHandling.ts`](https://github.com/every-app/open-seo/blob/main/errorHandling.ts)).

## Entry Points and Application Bootstrap

### src/start.ts: The TanStack Start Instance

The root file [`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts) bootstraps the entire application by creating the TanStack React-Start instance. It wires the global middleware pipeline and configures CSRF protection for server functions:

```ts
// 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,
}));

```

*Source:* [`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts)

### src/routeTree.gen.ts: Client-Side Routing

This auto-generated file at the root of `src` defines the client-side route tree, mapping URLs to their corresponding React components. It bridges the file-system routing convention with the TanStack Router configuration.

## How Code Flows Through the src Directory

Understanding the `src` directory requires tracing the request lifecycle:

1. **Bootstrap**: [`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts) initializes the application with middleware configurations.
2. **Routing**: [`src/routeTree.gen.ts`](https://github.com/every-app/open-seo/blob/main/src/routeTree.gen.ts) matches incoming URLs to page components.
3. **Middleware**: Functions in `src/middleware` authenticate the user and handle errors before business logic executes.
4. **Server Functions**: Logic in `src/serverFunctions` processes SEO data requests (rank checks, audits).
5. **Validation**: `src/types` Zod schemas validate external API responses and user inputs.
6. **Persistence**: `src/db` providers persist or retrieve data from SQLite/Postgres.
7. **Sharing**: `src/shared` utilities format the response data for the frontend.

## Practical Examples: Working with src Code

When extending OpenSEO, developers interact with `src` through predictable patterns. Server functions import from `shared` and `types`, while the database layer remains isolated from UI concerns.

**Database Schema Definition:**
The [`src/db/schema.ts`](https://github.com/every-app/open-seo/blob/main/src/db/schema.ts) file defines table structures using Drizzle syntax, which the provider then exposes to server functions.

**Middleware Application:**
Authentication checks in [`src/middleware/ensureUser.ts`](https://github.com/every-app/open-seo/blob/main/src/middleware/ensureUser.ts) run automatically for every server function call, eliminating the need to manually verify sessions in each business logic file.

## Summary

- The `src` directory contains **all application source code** for OpenSEO, acting as the single source of truth for business logic.
- **`src/serverFunctions`** exposes TanStack server functions for SEO operations like rank tracking and keyword research.
- **`src/shared`** provides cross-platform utilities (JSON parsing, billing logic) used by both client and server.
- **`src/types`** maintains Zod schemas and TypeScript definitions for external API validation.
- **`src/db`** abstracts database access through Drizzle ORM with multi-provider support (Postgres/SQLite).
- **`src/middleware`** centralizes request pre-processing including authentication and CSRF protection.
- **[`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts)** bootstraps the TanStack Start instance with global middleware configuration.

## Frequently Asked Questions

### What is the main entry point for the OpenSEO application?

The main entry point is **[`src/start.ts`](https://github.com/every-app/open-seo/blob/main/src/start.ts)**, which creates the TanStack React-Start instance and configures global middleware including CSRF protection and server-function middleware pipelines. This file bootstraps the entire application before routing takes over.

### How does OpenSEO handle database connections in the src directory?

Database connections are abstracted through **[`src/db/provider.ts`](https://github.com/every-app/open-seo/blob/main/src/db/provider.ts)**, which exports a configured Drizzle ORM instance. The same provider supports multiple backends (SQLite for local development, Postgres for production) via environment variables, ensuring [`src/db/schema.ts`](https://github.com/every-app/open-seo/blob/main/src/db/schema.ts) definitions work uniformly across deployment targets.

### What is the purpose of the serverFunctions folder in src?

The **`src/serverFunctions`** directory implements TanStack's server-function API, exposing type-safe remote procedures that React components call directly. These functions handle SEO-specific operations—such as rank tracking in [`rank-tracking.ts`](https://github.com/every-app/open-seo/blob/main/rank-tracking.ts) and keyword research in [`keywords.ts`](https://github.com/every-app/open-seo/blob/main/keywords.ts)—while running exclusively on the server for API key security and heavy computation.

### Why does OpenSEO use Zod schemas in the src/types directory?

OpenSEO uses Zod schemas in **`src/types`** to enforce runtime validation of data exchanged with external APIs like DataForSEO and Google Search Console. These schemas—stored in files like [`src/types/schemas/keywords.ts`](https://github.com/every-app/open-seo/blob/main/src/types/schemas/keywords.ts)—provide type safety beyond TypeScript compilation, catching malformed responses before they propagate into the application logic or database.