> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fjall.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Network Factory

> Create AWS VPC networking with the Fjall NetworkFactory: subnets, NAT gateways, VPC endpoints, and Transit Gateway.

## Overview

`NetworkFactory` creates VPC and networking infrastructure on AWS. Fjall configures networking automatically when you create an application. Use `NetworkFactory` directly when you need custom networking.

## Automatic Networking

When you create an application, Fjall automatically provisions:

### VPC Configuration

* **CIDR blocks**: Managed by IPAM
* **Availability zones**: Multi-AZ by default
* **Subnets**: Public and private subnets per AZ
* **NAT gateways**: For private subnet internet access
* **VPC endpoints**: For AWS service access

### Security Groups

* **Automatic rules**: Based on resource connections
* **Least privilege**: Only required ports opened
* **Dynamic updates**: As resources are added

### Load Balancers

* **Application Load Balancer**: For ECS services
* **Target groups**: Automatic health checks
* **SSL termination**: With ACM certificates

## Current Implementation

### Through App Class

```typescript theme={null}
const app = App.getApp("myapp");
// VPC is automatically created and configured
```

### Through Compute Factory

```typescript theme={null}
app.addCompute(
  ComputeFactory.build("api", {
    type: "ecs",
    cluster: {
      domain: "api.example.com",
      domainConfig: { certificateArn: "arn:aws:acm:..." },
    },
    services: [
      {
        name: "api",
        capacityProvider: "FARGATE",
        containers: [{ port: 3000 }],
      },
    ],
    // ALB and target groups created automatically
  }),
);
```

### Through Database Factory

```typescript theme={null}
app.addDatabase(
  DatabaseFactory.build("MyDB", {
    type: "Aurora",
    databaseName: "MyDatabase",
    // Security groups and subnet groups configured automatically
  }),
);
```

## Connection Management

Declare connections on a service and Fjall wires the security group rules:

```typescript theme={null}
const storage = app.addStorage(...);

const web = app.addCompute(
  ComputeFactory.build("web", {
    type: "ecs",
    services: [
      {
        name: "web",
        capacityProvider: "FARGATE",
        containers: [{ port: 3000 }],
        connections: [storage], // Security group rules added automatically
      },
    ],
  }),
);
```

## NetworkFactory Usage

### Basic Usage

```typescript theme={null}
import { App, NetworkFactory } from "@fjall/components-infrastructure";

const app = App.getApp("myapp");

const network = app.addNetwork(
  NetworkFactory.build("MainVPC", {
    maxAzs: 2,
  }),
);
```

### Full Configuration

```typescript theme={null}
const network = app.addNetwork(
  NetworkFactory.build("MainVPC", {
    vpcName: "production-vpc",
    maxAzs: 3,
    cidrMask: 24,
    natGateways: {
      count: 2, // One per AZ for HA
    },
    flowLogs: {
      destination: "cloudwatch",
      retentionDays: 30,
      trafficType: "ALL",
    },
    vpcEndpoints: {
      gateway: { s3: true, dynamodb: true },
      interface: { ecr: true, secretsManager: true, ssm: true },
    },
  }),
);
```

### Parameters

| Parameter                | Type                                                           | Description                               | Default        |
| ------------------------ | -------------------------------------------------------------- | ----------------------------------------- | -------------- |
| `vpcName`                | string                                                         | Custom VPC name                           | App name       |
| `maxAzs`                 | number                                                         | Number of availability zones              | `2`            |
| `cidrMask`               | number                                                         | Subnet CIDR mask                          | `24`           |
| `natGateways`            | `{ count: number }` or `false`                                 | NAT gateway config, or `false` to disable | `{ count: 1 }` |
| `flowLogs`               | `{ destination, retentionDays?, trafficType? }` or `false`     | Flow logs config                          | Disabled       |
| `flowLogs.destination`   | `"cloudwatch" \| "s3"`                                         | Log destination                           | -              |
| `flowLogs.retentionDays` | number                                                         | CloudWatch log retention (days)           | `14`           |
| `flowLogs.trafficType`   | `"ALL" \| "ACCEPT" \| "REJECT"`                                | Traffic to log                            | `"ALL"`        |
| `vpcEndpoints`           | object or `false`                                              | VPC endpoint configuration                | None           |
| `vpcEndpoints.gateway`   | `{ s3?: boolean, dynamodb?: boolean }`                         | Gateway endpoints                         | `{}`           |
| `vpcEndpoints.interface` | `{ ecr?, secretsManager?, kms?, ssm?, sts?, cloudwatchLogs? }` | Interface endpoints                       | `{}`           |
| `subnets`                | object                                                         | Custom subnet configuration               | Auto           |
| `transitGateway`         | `{ id: string }`                                               | Transit Gateway attachment                | None           |

### Disabling NAT Gateways

For cost savings in development:

```typescript theme={null}
const network = app.addNetwork(
  NetworkFactory.build("DevVPC", {
    natGateways: false, // No NAT gateways (public subnets only)
  }),
);
```

### VPC Endpoints for Private Access

Reduce data transfer costs and improve security. Gateway endpoints support `s3` and `dynamodb`. Interface endpoints support `ecr`, `secretsManager`, `kms`, `ssm`, `sts`, and `cloudwatchLogs`:

```typescript theme={null}
const network = app.addNetwork(
  NetworkFactory.build("SecureVPC", {
    vpcEndpoints: {
      gateway: { s3: true, dynamodb: true },
      interface: {
        ecr: true,
        secretsManager: true,
        kms: true,
        ssm: true,
        sts: true,
        cloudwatchLogs: true,
      },
    },
  }),
);
```

### Transit Gateway Integration

Connect VPCs across accounts:

```typescript theme={null}
const network = app.addNetwork(
  NetworkFactory.build("ConnectedVPC", {
    transitGateway: {
      id: "tgw-0123456789abcdef0",
    },
  }),
);
```

## Best Practices

1. **Let Fjall manage networking** - Automatic configuration handles most use cases
2. **Use IPAM** - Prevents CIDR conflicts across accounts
3. **Multi-AZ deployment** - Enabled by default for resilience
4. **Private subnets** - Databases always in private subnets
5. **VPC endpoints** - Reduces data transfer costs

## Next Steps

<CardGroup cols={2}>
  <Card title="Compute Factory" icon="server" href="/patterns/compute-factory">
    Deploy ECS and Lambda applications behind the VPC.
  </Card>

  <Card title="Database Factory" icon="database" href="/patterns/database-factory">
    Provision Aurora, RDS, and DynamoDB in private subnets.
  </Card>

  <Card title="Storage Factory" icon="box-archive" href="/patterns/storage-factory">
    Create S3 buckets with VPC gateway endpoint access.
  </Card>

  <Card title="Standard Pattern" icon="layer-group" href="/patterns/standard-pattern">
    Compose a full application with networking included.
  </Card>
</CardGroup>
