JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 14
  • Score
    100M100P100Q46557F
  • License MIT

NestJS module for Cloudflare R2 storage integration with S3-compatible API

Package Exports

  • nestjs-r2
  • nestjs-r2/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nestjs-r2) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Nestjs R2

NestJS module for integration with Cloudflare R2 storage

npm version npm downloads bundle size license PRs Welcome

A NestJS module for seamless integration with Cloudflare R2 storage, providing S3-compatible file operations with TypeScript support.

Table of Contents

Installation

npm install nestjs-r2
# or
yarn add nestjs-r2
# or
pnpm add nestjs-r2

Quick Start

1. Register the Module

Synchronous Registration

import { Module } from "@nestjs/common";
import { R2Module } from "nestjs-r2";

@Module({
  imports: [
    R2Module.register({
      accountId: "your-cloudflare-account-id",
      accessKeyId: "your-r2-access-key-id",
      secretAccessKey: "your-r2-secret-access-key",
      bucket: "your-bucket-name",
      publicUrl: "https://your-public-domain.com", // optional
    }),
  ],
})
export class AppModule {}

Asynchronous Registration

Using Factory Function
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { R2Module } from "nestjs-r2";

@Module({
  imports: [
    ConfigModule.forRoot(),
    R2Module.registerAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        accountId: configService.get("CLOUDFLARE_ACCOUNT_ID"),
        accessKeyId: configService.get("R2_ACCESS_KEY_ID"),
        secretAccessKey: configService.get("R2_SECRET_ACCESS_KEY"),
        bucket: configService.get("R2_BUCKET"),
        publicUrl: configService.get("R2_PUBLIC_URL"),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
Using Configuration Class
import { Injectable, Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { R2Module, R2ModuleOptions, R2OptionsFactory } from "nestjs-r2";

@Injectable()
export class R2ConfigService implements R2OptionsFactory {
  constructor(private configService: ConfigService) {}

  createR2Options(): R2ModuleOptions {
    return {
      accountId: this.configService.get("CLOUDFLARE_ACCOUNT_ID"),
      accessKeyId: this.configService.get("R2_ACCESS_KEY_ID"),
      secretAccessKey: this.configService.get("R2_SECRET_ACCESS_KEY"),
      bucket: this.configService.get("R2_BUCKET"),
      publicUrl: this.configService.get("R2_PUBLIC_URL"),
    };
  }
}

@Module({
  imports: [
    R2Module.registerAsync({
      useClass: R2ConfigService,
    }),
  ],
  providers: [R2ConfigService],
})
export class AppModule {}
Using Existing Service
import { Module } from "@nestjs/common";
import { R2Module } from "nestjs-r2";
import { MyExistingConfigService } from "./my-existing-config.service";

@Module({
  imports: [
    R2Module.registerAsync({
      useExisting: MyExistingConfigService,
    }),
  ],
  providers: [MyExistingConfigService],
})
export class AppModule {}

2. Use the Service

import { Injectable } from "@nestjs/common";
import { R2Service } from "nestjs-r2";

@Injectable()
export class FileService {
  constructor(private readonly r2Service: R2Service) {}

  async uploadFile(file: Express.Multer.File) {
    const result = await this.r2Service.upload(file);
    return {
      key: result.key,
      url: result.url, // Public URL if configured
    };
  }

  async downloadFile(key: string) {
    const stream = await this.r2Service.get(key);
    return stream;
  }

  async deleteFile(key: string) {
    const result = await this.r2Service.delete(key);
    return result;
  }
}

3. Complete Controller Example

import {
  Controller,
  Post,
  Get,
  Delete,
  Param,
  UseInterceptors,
  UploadedFile,
  Res,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { Response } from "express";
import { R2Service } from "nestjs-r2";

@Controller("files")
export class FileController {
  constructor(private readonly r2Service: R2Service) {}

  @Post("upload")
  @UseInterceptors(FileInterceptor("file"))
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    const result = await this.r2Service.upload(file);
    return {
      message: "File uploaded successfully",
      key: result.key,
      url: result.url,
    };
  }

  @Get(":key")
  async downloadFile(@Param("key") key: string, @Res() res: Response) {
    const stream = await this.r2Service.get(key);
    stream.pipe(res);
  }

  @Delete(":key")
  async deleteFile(@Param("key") key: string) {
    const result = await this.r2Service.delete(key);
    return {
      message: "File deleted successfully",
      ...result,
    };
  }
}

API Reference

R2Service

upload(file: any): Promise<{ key: string; url: string | null }>

Uploads a file to R2 storage.

Parameters:

  • file: File object with originalname, buffer, and mimetype properties

Returns:

  • key: Generated unique key for the file
  • url: Public URL if publicUrl is configured, otherwise null

get(key: string): Promise<Readable>

Downloads a file from R2 storage.

Parameters:

  • key: The file key

Returns:

  • Readable: Node.js readable stream

delete(key: string): Promise<{ deleted: boolean }>

Deletes a file from R2 storage.

Parameters:

  • key: The file key

Returns:

  • deleted: Boolean indicating success

Configuration Options

R2ModuleOptions

interface R2ModuleOptions {
  accountId: string; // Cloudflare Account ID
  accessKeyId: string; // R2 Access Key ID
  secretAccessKey: string; // R2 Secret Access Key
  bucket: string; // R2 Bucket name
  publicUrl?: string; // Optional public URL for file access
}

R2ModuleAsyncOptions

interface R2ModuleAsyncOptions {
  imports?: any[]; // Optional modules to import
  useFactory?: (...args: any[]) => Promise<R2ModuleOptions> | R2ModuleOptions;
  useClass?: Type<R2OptionsFactory>;
  useExisting?: Type<R2OptionsFactory>;
  inject?: any[]; // Dependencies to inject (used with useFactory)
}

R2OptionsFactory

interface R2OptionsFactory {
  createR2Options(): Promise<R2ModuleOptions> | R2ModuleOptions;
}

Environment Variables

Create a .env file in your project root:

CLOUDFLARE_ACCOUNT_ID=your-account-id
R2_ACCESS_KEY_ID=your-access-key-id
R2_SECRET_ACCESS_KEY=your-secret-access-key
R2_BUCKET=your-bucket-name
R2_PUBLIC_URL=https://your-public-domain.com

Getting Cloudflare R2 Credentials

  1. Sign up for Cloudflare and navigate to R2 Object Storage
  2. Create an R2 bucket in your desired region
  3. Generate API tokens:
    • Go to "Manage R2 API tokens"
    • Click "Create API token"
    • Select permissions for your bucket
    • Note down the Access Key ID and Secret Access Key
  4. Find your Account ID in the right sidebar of the Cloudflare dashboard
  5. Set up custom domain (optional) for public file access

Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

v1.0.0

  • Initial release
  • Basic R2 integration with upload, download, and delete operations
  • Support for both sync and async module registration
  • TypeScript support
  • Comprehensive test coverage