Skip to content

Memoize the R2 S3Client and validate its environment variables with readable errors #45

Description

@royalpinto007

Problem

lib/r2/upload.ts constructs a brand new S3Client on every call:

function getR2Client() {
  return new S3Client({ region: "auto", endpoint: R2_ENDPOINT, credentials: { ... } });
}

Both getPresignedUploadUrl and getPresignedReadUrl call it, so each presign request builds a fresh client and its middleware stack.

Additionally, the credentials are read with non-null assertions (process.env.R2_ACCESS_KEY_ID!). If they are unset the failure surfaces as an obscure SDK error at signing time rather than a clear startup error, unlike getR2PublicBaseUrl() a few lines below which does throw a readable message.

Suggested approach

  1. Memoize the client in a module level variable, created lazily on first use.
  2. Validate R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and R2_BUCKET_NAME at client construction and throw a message naming the missing variable, matching the style of the existing NEXT_PUBLIC_R2_PUBLIC_URL error.

Done when

  • Repeated presign calls reuse one client instance.
  • A missing R2 environment variable produces an error that names the variable.
  • A test covers the missing-variable message.

Good first issue: the file is under 80 lines and the change is local to it.


If you want to take this on, comment on the issue to claim it and it will be assigned. Please keep to a maximum of 2 open claims per person at a time so other contributors get a chance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions