npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nilovonjs/bucketkit-core

v0.1.1

Published

S3 Upload Library for Node.js - Core utilities for presigned URLs, validation, and upload policies

Readme

📦 @nilovonjs/bucketkit-core

Backend utilities for S3 uploads - Generate presigned URLs, validate uploads, and manage storage policies.

🎯 Overview

@nilovonjs/bucketkit-core provides server-side utilities for handling S3 (and S3-compatible) file uploads. It generates secure presigned URLs, validates upload requests, and manages file storage paths.

✨ Features

  • 🔐 Presigned URLs - Generate secure upload URLs for direct-to-S3 uploads
  • Validation - Validate file size, MIME types, and custom rules
  • 📁 Path Resolution - Organize files with custom path patterns
  • 🛡️ Error Handling - Typed errors for easy handling
  • 🔌 S3 Compatible - Works with AWS S3, MinIO, Cloudflare R2, and more
  • 📝 Full TypeScript - Complete type safety with strict types

🚀 Installation

npm install @nilovonjs/bucketkit-core
# or
pnpm add @nilovonjs/bucketkit-core
# or
yarn add @nilovonjs/bucketkit-core

📖 Quick Start

Basic Usage

import { createBucketKit } from '@nilovonjs/bucketkit-core';

const bucketKit = createBucketKit({
  provider: 'aws-s3',
  region: 'us-east-1',
  bucket: 'my-uploads',
  defaultUploadPolicy: {
    maxSize: 10 * 1024 * 1024, // 10 MB
    allowedMimeTypes: ['image/*', 'application/pdf'],
  },
});

// Create a presigned upload URL
const result = await bucketKit.createPresignedUpload({
  fileName: 'photo.jpg',
  contentType: 'image/jpeg',
  size: 1024 * 1024,
});

console.log(result.url); // Presigned S3 URL
console.log(result.key); // Storage path: "uploads/2024/01/photo.jpg"
console.log(result.publicUrl); // Public URL after upload

Express.js API Route

import express from 'express';
import { createBucketKit } from '@nilovonjs/bucketkit-core';
import { BucketKitError, isBucketKitError } from '@nilovonjs/bucketkit-core';

const app = express();
app.use(express.json());

const bucketKit = createBucketKit({
  provider: 'aws-s3',
  region: process.env.S3_REGION!,
  bucket: process.env.S3_BUCKET!,
  credentials: {
    accessKeyId: process.env.S3_ACCESS_KEY_ID!,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
  },
  defaultUploadPolicy: {
    maxSize: 10 * 1024 * 1024,
    allowedMimeTypes: ['image/*'],
  },
});

app.post('/api/upload', async (req, res) => {
  try {
    const { fileName, contentType, size } = req.body;

    // Validate the upload request
    const validation = bucketKit.validateUploadRequest({
      fileName,
      contentType,
      size,
    });

    if (!validation.valid) {
      return res.status(400).json({ error: validation.error });
    }

    // Create presigned URL
    const result = await bucketKit.createPresignedUpload({
      fileName,
      contentType,
      size,
    });

    res.json(result);
  } catch (error) {
    if (isBucketKitError(error)) {
      return res.status(400).json({ error: error.message });
    }
    res.status(500).json({ error: 'Internal server error' });
  }
});

🔧 Configuration

Environment Variables

You can configure BucketKit using environment variables instead of passing them in code:

BUCKETKIT_S3_REGION=us-east-1
BUCKETKIT_S3_BUCKET=my-bucket
BUCKETKIT_S3_ACCESS_KEY_ID=your-access-key
BUCKETKIT_S3_SECRET_ACCESS_KEY=your-secret-key
// Credentials and config will be read from environment
const bucketKit = createBucketKit({
  provider: 'aws-s3',
  // region and bucket can be omitted if set in env
  defaultUploadPolicy: {
    maxSize: 10 * 1024 * 1024,
  },
});

Custom Path Resolver

Organize files with custom path patterns:

const bucketKit = createBucketKit({
  provider: 'aws-s3',
  region: 'us-east-1',
  bucket: 'my-uploads',
  defaultUploadPolicy: {
    pathResolver: ({ fileName, userId, category }) => {
      // Custom path: "users/{userId}/{category}/{fileName}"
      return `users/${userId}/${category}/${fileName}`;
    },
  },
});

S3-Compatible Storage

Works with MinIO, Cloudflare R2, and other S3-compatible services:

// MinIO
const bucketKit = createBucketKit({
  provider: 'aws-s3',
  region: 'us-east-1',
  bucket: 'my-uploads',
  endpoint: 'https://minio.example.com',
  forcePathStyle: true, // Required for MinIO
  credentials: {
    accessKeyId: 'minioadmin',
    secretAccessKey: 'minioadmin',
  },
});

// Cloudflare R2
const bucketKit = createBucketKit({
  provider: 'aws-s3',
  region: 'auto',
  bucket: 'my-uploads',
  endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
});

📚 API Reference

createBucketKit(config: BucketKitConfig): BucketKit

Creates a BucketKit instance with the provided configuration.

Configuration Options:

  • provider: 'aws-s3' - Storage provider (currently only AWS S3)
  • region: string - AWS region or S3-compatible region
  • bucket: string - S3 bucket name
  • credentials?: S3Credentials - Optional credentials (can use env vars)
  • endpoint?: string - Custom endpoint for S3-compatible services
  • forcePathStyle?: boolean - Use path-style URLs (required for MinIO)
  • defaultUploadPolicy?: UploadPolicy - Default validation policy

bucketKit.createPresignedUpload(params): Promise<PresignedUploadResult>

Generates a presigned URL for uploading a file.

Parameters:

  • fileName: string - Original file name
  • contentType: string - MIME type (e.g., 'image/jpeg')
  • size: number - File size in bytes
  • policy?: Partial<UploadPolicy> - Optional policy overrides

Returns:

{
  url: string;           // Presigned upload URL
  method: 'PUT';         // HTTP method
  headers: Record<string, string>; // Required headers
  key: string;           // Storage key/path
  publicUrl: string;     // Public URL after upload
  expiresIn: number;     // Expiration in seconds
}

bucketKit.validateUploadRequest(params): ValidationResult

Validates an upload request against the configured policy.

Parameters:

  • fileName: string
  • contentType: string
  • size: number
  • policy?: Partial<UploadPolicy> - Optional policy overrides

Returns:

{
  valid: boolean;
  error?: string;
}

bucketKit.getPublicUrl(key: string): string

Gets the public URL for a stored file.

🛡️ Error Handling

BucketKit provides typed errors for easy handling:

import { BucketKitError, isBucketKitError } from '@nilovonjs/bucketkit-core';

try {
  const result = await bucketKit.createPresignedUpload({ ... });
} catch (error) {
  if (isBucketKitError(error)) {
    switch (error.code) {
      case 'VALIDATION_ERROR':
        console.error('Validation failed:', error.message);
        break;
      case 'MISSING_CREDENTIALS':
        console.error('S3 credentials not configured');
        break;
      default:
        console.error('Upload error:', error.message);
    }
  } else {
    // Handle other errors
  }
}

Error Codes:

  • VALIDATION_ERROR - Upload validation failed
  • MISSING_CREDENTIALS - S3 credentials not provided
  • MISSING_CONFIG - Required configuration missing
  • S3_ERROR - AWS S3 operation failed

🔗 Related Packages

📄 License

MIT