Foundry24 in Denver

Turning Project Setup into a Reusable Library

Robbie infrastructure-as-code · cdk · reusable-components · design-systems

Every new project needs authentication, database configuration and migrations, CI/CD pipelines, API patterns and error handling, UI components, and deployment infrastructure. All of it takes time away from the product, so I keep mine in two private libraries. cdk-app-patterns holds AWS stacks, and this site and another product of mine both depend on it. mobile-kit holds the shared code for my apps, including auth, analytics and subscriptions.

Infrastructure components with CDK

A static site needs an S3 bucket, a CloudFront distribution in front of it, a cache policy and an HTTPS redirect. Instead of writing that for every project, create a construct.

// packages/constructs/src/static-site.ts
import { RemovalPolicy } from "aws-cdk-lib";
import * as acm from "aws-cdk-lib/aws-certificatemanager";
import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
import * as origins from "aws-cdk-lib/aws-cloudfront-origins";
import * as s3 from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";

export interface StaticSiteProps {
  domainName?: string;
  certificate?: acm.ICertificate;
  removalPolicy?: RemovalPolicy;
}

export class StaticSite extends Construct {
  public readonly bucket: s3.Bucket;
  public readonly distribution: cloudfront.Distribution;

  constructor(scope: Construct, id: string, props: StaticSiteProps) {
    super(scope, id);

    this.bucket = new s3.Bucket(this, "Bucket", {
      removalPolicy: props.removalPolicy ?? RemovalPolicy.RETAIN,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      encryption: s3.BucketEncryption.S3_MANAGED,
    });

    this.distribution = new cloudfront.Distribution(this, "Distribution", {
      defaultBehavior: {
        origin: origins.S3BucketOrigin.withOriginAccessControl(this.bucket),
        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
        cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
      },
      domainNames: props.domainName ? [props.domainName] : undefined,
      certificate: props.certificate,
      defaultRootObject: "index.html",
      // SPA routing. S3 answers 403 for a missing key unless CloudFront can list the bucket.
      errorResponses: [403, 404].map((httpStatus) => ({
        httpStatus,
        responseHttpStatus: 200,
        responsePagePath: "/index.html",
      })),
    });
  }
}

A project then only passes its domain and certificate.

const site = new StaticSite(this, "Frontend", {
  domainName: "app.example.com",
  certificate: cert,
});

Composing larger patterns

Once you have a few constructs, a whole application stack gets short. This one is a sketch. PostgresDatabase and FargateApi stand for constructs you’d write the same way as StaticSite, and they don’t exist in aws-cdk-lib.

export class WebAppStack extends Stack {
  constructor(scope: Construct, id: string, props: WebAppProps) {
    super(scope, id, props);

    const database = new PostgresDatabase(this, "Database", {
      instanceSize: props.instanceSize,
      vpc: props.vpc,
    });

    new FargateApi(this, "Api", {
      vpc: props.vpc,
      database,
      image: props.apiImage,
    });

    new StaticSite(this, "Frontend", {
      domainName: props.domainName,
      certificate: props.certificate,
    });
  }
}

Design system components

Frontend code works the same way. Write one button rather than styling it differently in every project.

// components/Button.tsx
import type { ReactNode } from "react";
import clsx from "clsx";
import { Spinner } from "./Spinner";

const variants = {
  primary: "bg-blue-600 text-white hover:bg-blue-700",
  secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200",
  danger: "bg-red-600 text-white hover:bg-red-700",
};

const sizes = {
  sm: "px-2 py-1 text-sm",
  md: "px-4 py-2",
  lg: "px-6 py-3 text-lg",
};

interface ButtonProps {
  variant: "primary" | "secondary" | "danger";
  size: "sm" | "md" | "lg";
  loading?: boolean;
  children: ReactNode;
  onClick?: () => void;
}

export function Button({ variant, size, loading, children, onClick }: ButtonProps) {
  return (
    <button
      className={clsx(
        "rounded font-medium transition-colors",
        variants[variant],
        sizes[size],
        loading && "opacity-50 cursor-not-allowed"
      )}
      onClick={onClick}
      disabled={loading}
    >
      {loading ? <Spinner size={size} /> : children}
    </button>
  );
}

It shows a spinner while loading and disables itself until the load finishes, and every page uses the same one. Spinner is another component in the same package.

When to extract

Setup and plumbing that repeat between projects are good candidates. Business logic and one-off integrations usually aren’t.

My rule of thumb is that if you’ve built it three times, it’s a candidate for extraction. If it requires heavy customization per use, keep it project-specific.

Extract code that has already shipped. The first subscriptions package in mobile-kit was a skeleton that never went into an app. It returned “unknown” for every subscription purchase, and its tests were thorough and mostly documented its defects. I replaced it with the subscription code from David, one of my apps, because that code had handled real purchases. The app-specific parts became config and callbacks, and David’s tests came across as the spec.

Versioning and publishing

For infrastructure components, publish to a private npm registry.

{
  "name": "@yourorg/constructs",
  "version": "1.2.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts"
}

Projects depend on a semver range.

{
  "dependencies": {
    "@yourorg/constructs": "^1.2.0"
  }
}

Bug fixes and better defaults reach each project on its next update. In one of my apps, changing the distance unit on the settings screen left the tab behind it showing miles until the app restarted. The shared useStorage hook never told other mounted components about a write, and no app could fix that from outside. I fixed it once in the library, for every app that stores a preference.

A bug in a shared component affects everything, so test the components and not just the projects. In mobile-kit, a token response without expires_in stored the expiry as NaN. Every comparison against NaN is false, so the session looked fresh forever. Eventually every request got a 401, with no way back short of a reinstall. The first test suite had high line coverage, but about ten of its tests asserted known-wrong behavior, so fixing those bugs broke CI. I fixed the source and rewrote those tests to assert what should happen.

Publishing fails too, and it can fail for a long time before you notice. At one point every mobile-kit tag since v0.3.0 had failed and published nothing. GitHub Packages ties a package to the repository that first published it, and analytics started in another repository. The workflow couldn’t see the existing version, tried to publish it again and got a 403. That killed the run, and analytics sorts first, so no other package got a turn. Now a failure gets recorded, the loop carries on, and the run reports every failure at the end.

Swift packages have a different trap. They resolve git tags, so a merged PR doesn’t reach an app until a tag exists. Tempo sat on v0.1.0 for five commits that way.

Where to start

If you don’t have one yet, look through your last three projects for code that was nearly identical. Authentication, database setup and deployment are common starting points. Extract the most repeated pattern and use it in your next project. I’d add the second component when a project needs it.

Foundry24 builds and runs software for small businesses

AI agents, automation, and websites, built in a few weeks and then maintained for a monthly fee. If something in your week should be software by now, book a call.

Send a message

It goes to hello@foundry24.io. Replies usually come within a day.