Skip to content

About

Universal file upload SDK for Node.js supporting R2, AWS S3, Cloudinary, and local storage with a single unified API.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

OneBucket

One SDK. Any storage provider.

Stop juggling S3, R2, Cloudinary, and local disk APIs. OneBucket gives you one clean interface for all of them. Upload a file in 3 lines. Switch providers by changing one string. That's it.

pnpm add one-bucket

Batteries included — S3, R2, Cloudinary, and local storage all work out of the box. No extra installs.


Quick Start

import { createOneBucket } from "one-bucket";

const storage = createOneBucket({
  provider: "s3",
  bucket: "my-bucket",
  region: "us-east-1",
  credentials: {
    accessKey: process.env.AWS_ACCESS_KEY!,
    secretKey: process.env.AWS_SECRET_KEY!,
  },
});

await storage.upload({ file: buffer, path: "avatars/me.png" });

Done. That's a file in S3.

Want R2 instead? Change one word:

const storage = createOneBucket({ provider: "r2", ... });

Your upload code doesn't change. Nothing else changes.


Providers

AWS S3
createOneBucket({
  provider: "s3",
  bucket: "my-bucket",
  region: "us-east-1",
  credentials: { accessKey: "...", secretKey: "..." },
  domain: "https://cdn.myapp.com",  // optional — custom domain
  encryption: { enabled: true, type: "AES256" },  // optional
});
Cloudflare R2
createOneBucket({
  provider: "r2",
  bucket: "my-bucket",
  accountId: "your-account-id",
  credentials: { accessKey: "...", secretKey: "..." },
  domain: "https://cdn.myapp.com",  // optional
});
Cloudinary
createOneBucket({
  provider: "cloudinary",
  cloudName: "my-cloud",
  apiKey: "...",
  apiSecret: "...",
  folder: "uploads",  // optional
});
Local Disk
createOneBucket({
  provider: "local",
  directory: "./uploads",
  baseUrl: "http://localhost:3000/files",  // optional
});

API

Every provider supports the same methods. Learn once, use everywhere.

// upload a file
await storage.upload({ file: buffer, path: "photos/1.png" });

// download it
const { body, size } = await storage.download("photos/1.png");

// check if it exists
const exists = await storage.exists("photos/1.png");

// get the public URL
const url = await storage.getUrl("photos/1.png");

// generate a temporary signed URL
const signed = await storage.getSignedUrl("photos/1.png", { expiresIn: 3600 });

// list files
const { files } = await storage.list({ prefix: "photos/" });

// delete it
await storage.delete("photos/1.png");

// generate a presigned upload URL (for direct client uploads)
const uploadUrl = await storage.createUploadUrl({ path: "uploads/image.png" });

The file param accepts a Buffer, Readable stream, file path string, or base64 string. Content type is auto-detected.


NestJS

First-class NestJS support via one-bucket/nestjs.

Register the module:

import { OneBucketModule } from "one-bucket/nestjs";

@Module({
  imports: [
    OneBucketModule.forRoot({
      provider: "r2",
      bucket: "uploads",
      accountId: "...",
      credentials: { accessKey: "...", secretKey: "..." },
    }),
  ],
})
export class AppModule {}

Inject and use:

import { OneBucketService } from "one-bucket/nestjs";

@Injectable()
export class UploadService {
  constructor(private readonly storage: OneBucketService) {}

  async uploadAvatar(file: Buffer, userId: string) {
    return this.storage.upload({
      file,
      path: `avatars/${userId}.png`,
    });
  }
}

Async config with ConfigService works too — use OneBucketModule.forRootAsync().


Error Handling

Every error OneBucket throws extends OneBucketError. No random untyped exceptions leaking from provider SDKs. Every error has a .code you can switch on and a human-readable .message.

import { OneBucketError, FileNotFoundError } from "one-bucket";

try {
  await storage.download("nope.txt");
} catch (err) {
  if (err instanceof FileNotFoundError) {
    console.log(err.filePath);  // "nope.txt"
    console.log(err.code);      // "FILE_NOT_FOUND"
  }
}
Error Code When
InvalidConfigError INVALID_CONFIG Bad or missing config
FileNotFoundError FILE_NOT_FOUND File doesn't exist
UploadFailedError UPLOAD_FAILED Upload went wrong
ProviderError PROVIDER_ERROR Provider SDK error
OperationNotSupportedError OPERATION_NOT_SUPPORTED e.g. signed URLs on local

Migration

Move files between any two providers with one function call.

import { createOneBucket, migrate } from "one-bucket";

const source = createOneBucket({
  provider: "s3",
  bucket: "old-bucket",
  region: "us-east-1",
  credentials: { accessKey: "...", secretKey: "..." },
});

const target = createOneBucket({
  provider: "r2",
  bucket: "new-bucket",
  accountId: "...",
  credentials: { accessKey: "...", secretKey: "..." },
});

const result = await migrate(source, target, {
  prefix: "uploads/",
  concurrency: 10,
});

console.log(`${result.completed}/${result.total} files migrated`);

Options:

Option Type Default Description
prefix string — Only migrate files under this prefix
concurrency number 5 Max parallel transfers
overwrite boolean false Overwrite existing files in target
dryRun boolean false List files without transferring
onProgress function — Called after each file with { total, completed, failed, skipped, currentFile }
onError function — Called on failure — return "skip" to continue or "abort" to stop

Dry run — preview what would be migrated:

const result = await migrate(source, target, {
  prefix: "images/",
  dryRun: true,
});

console.log(result.files); // [{ path: "images/1.png", size: 4096 }, ...]

Progress tracking:

await migrate(source, target, {
  onProgress: ({ completed, total, failed }) => {
    console.log(`${completed}/${total} done, ${failed} failed`);
  },
  onError: (err) => {
    console.error(`Failed: ${err.path} — ${err.error.message}`);
    return "skip";
  },
});

Debug Logging

DEBUG_ONEBUCKET=true

Requirements

  • Node.js 18+
  • TypeScript 5+ (recommended)

License

MIT

About

Universal file upload SDK for Node.js supporting R2, AWS S3, Cloudinary, and local storage with a single unified API.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages