Skip to content

Storage ​

Storage reads and writes files on named disks. A disk is a folder on the server or a bucket in the cloud. Every disk has the same methods, so code written against the local disk works on S3, Azure or Google Cloud Storage unchanged.

DriverStores files inNeeds
localA folder on the serverNothing
s3Amazon S3, or an S3-compatible service@aws-sdk/client-s3, @aws-sdk/s3-request-presigner
azureAzure Blob Storage@azure/storage-blob
gcsGoogle Cloud Storage@google-cloud/storage

The cloud SDKs are optional peer dependencies. Install the one you use:

sh
npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
npm i @azure/storage-blob
npm i @google-cloud/storage

Using a disk whose SDK isn't installed throws a StorageError that names the package to install.

Disks ​

Without any setup there is one disk, local, rooted at <cwd>/storage. Add disks with app.useStorage():

ts
app.useStorage({
  default: 'local',
  disks: {
    local: { driver: 'local', root: 'storage' },
    s3: {
      driver: 's3',
      bucket: process.env.S3_BUCKET!,
      region: process.env.AWS_REGION,
    },
  },
});

default names the disk used when no name is given (local if left out). The local disk is always there unless you replace it. Bad settings, such as a missing bucket or an unknown driver, throw at startup.

useStorage() also takes an @AppConfig class that returns the same object, so the settings can live in src/config/storage.config.ts:

ts
import { AppConfig, Environment, MeghConfig, StorageConfig } from '@meghjs/core';

@AppConfig
export class StorageSettings extends MeghConfig<StorageConfig> {
  config(env: Environment): StorageConfig {
    return {
      default: env.get('STORAGE_DISK') ?? 'local',
      disks: {
        s3: {
          driver: 's3',
          bucket: env.getOrThrow('S3_BUCKET'),
          region: env.get('AWS_REGION'),
        },
      },
    };
  }
}
ts
app.useStorage(StorageSettings);

Using a disk ​

Inject Storage and pick a disk with disk(name?):

ts
import { AppService, Storage } from '@meghjs/core';

@AppService
export class AvatarService {
  constructor(private readonly storage: Storage) {}

  async save(userId: string, image: Buffer) {
    const path = `avatars/${userId}.png`;
    await this.storage.disk('s3').put(path, image);
    return this.storage.disk('s3').url(path);
  }
}

Or inject one disk with @InjectDisk(name?). Leave the name out for the default disk:

ts
import { AppService, Disk, InjectDisk } from '@meghjs/core';

@AppService
export class ReportService {
  constructor(@InjectDisk('s3') private readonly disk: Disk) {}

  publish(id: string, pdf: Buffer) {
    return this.disk.put(`reports/${id}.pdf`, pdf);
  }
}

Storage.disk('s3') works outside classes too.

Methods ​

MethodDoes
put(path, data, { contentType?, visibility? })Writes a file, replacing any file at path. data is a Buffer, Uint8Array, string or readable stream
get(path)Reads the whole file as a Buffer
getStream(path)Reads the file as a stream
exists(path)true when the file is there
delete(path)Deletes the file. A missing file is not an error
copy(from, to)Copies a file, replacing any file at to
move(from, to)Moves a file, replacing any file at to
size(path)Size in bytes
lastModified(path)A Date
list(dir?)Every file under dir (the whole disk when left out), recursively, sorted
url(path)The public URL
temporaryUrl(path, expiresIn)A URL that reads the file for expiresIn seconds

Reading a missing file throws FileNotFoundException. It extends NotFoundException, so a controller that lets it through answers 404.

contentType defaults to one guessed from the extension. visibility is 'public' or 'private'; see each driver for what it does.

Paths ​

Paths are relative to the disk's root and use /. They are cleaned up the same way on every disk: a leading /, empty segments and ./ are dropped, and \ becomes /, so /avatars//./me.png and avatars\me.png both mean avatars/me.png.

A path with a .. segment, a null byte, or nothing left after cleaning is refused with a StorageError. On the local disk, a path can't leave the root, and neither can a symlink: one that points outside the root is refused when reading, writing and listing.

list('a') lists the folder a: it returns a/1.txt but not ab/2.txt.

Local disk ​

ts
local: {
  driver: 'local',
  root: 'storage',              // relative to the working directory
  url: '/storage',              // for url(); optional
  signer: (path, expiresAt) => signedRoute(path, expiresAt), // for temporaryUrl(); optional
}
  • url() needs url. Serve the folder yourself, for example with app.useStaticFiles({ root: path.join(process.cwd(), 'storage'), prefix: '/storage/' }).
  • temporaryUrl() throws unless you give a signer: a function that returns the URL, for example a route of your app that checks a signature.
  • visibility and contentType are ignored.

S3 ​

ts
s3: {
  driver: 's3',
  bucket: 'my-bucket',
  region: 'eu-west-1',
  credentials: { accessKeyId: '...', secretAccessKey: '...' }, // optional
  root: 'uploads',              // a folder in the bucket; optional
  url: 'https://cdn.example.com', // for url(); optional
  visibility: 'private',        // default for put(); optional
  options: { maxAttempts: 5 },  // extra S3Client options; optional
}

Without credentials, the AWS SDK finds them the usual way: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, a profile, or the instance's IAM role. region falls back to AWS_REGION.

  • url() is https://<bucket>.s3.<region>.amazonaws.com/<path>, or url plus the path when set. The object must be public for that URL to work.
  • temporaryUrl() is a presigned GetObject URL. S3 allows up to 7 days.
  • visibility is sent as an ACL (public-read or private). Buckets created since 2023 have ACLs turned off and refuse them, so only set it when your bucket uses ACLs. Without visibility, no ACL is sent.
  • Streams are uploaded in 8 MiB parts when they are bigger than one part, so memory use stays flat for large uploads.
  • client takes an S3Client you built yourself, in place of the connection settings.

S3-compatible services ​

Set endpoint (and forcePathStyle when the service wants the bucket in the path) to use any S3-compatible service:

ServiceSettings
Cloudflare R2endpoint: 'https://<account-id>.r2.cloudflarestorage.com', region: 'auto'
MinIOendpoint: 'http://localhost:9000', region: 'us-east-1', forcePathStyle: true
DigitalOcean Spacesendpoint: 'https://<region>.digitaloceanspaces.com', region: '<region>' (e.g. nyc3)
Backblaze B2endpoint: 'https://s3.<region>.backblazeb2.com', region: '<region>' (e.g. us-west-004)
Wasabiendpoint: 'https://s3.<region>.wasabisys.com', region: '<region>' (e.g. eu-central-1)
ts
r2: {
  driver: 's3',
  bucket: 'media',
  region: 'auto',
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
  url: 'https://media.example.com', // R2 buckets have no public address of their own
}

With an endpoint, url() is <endpoint>/<bucket>/<path> when forcePathStyle is on, and https://<bucket>.<endpoint host>/<path> otherwise. Most of these services don't support ACLs, so leave visibility out and make the bucket public (or not) in the service's console.

Azure Blob Storage ​

ts
azure: {
  driver: 'azure',
  container: 'uploads',
  connectionString: process.env.AZURE_STORAGE_CONNECTION_STRING,
}

Instead of a connection string, give accountName with accountKey, or with credential, a token credential such as new DefaultAzureCredential() from @azure/identity. endpoint overrides the blob service URL (https://<accountName>.blob.core.windows.net). For Azurite, the local emulator, use connectionString: 'UseDevelopmentStorage=true'.

  • url() is the blob's URL, or url plus the path when set. The container must allow public access for that URL to work.
  • temporaryUrl() is a read-only SAS URL. With an account key (or a connection string that has one), Megh signs it itself. With a token credential, it asks Azure for a user delegation key first, which needs the Storage Blob Delegator role.
  • visibility is ignored: Azure sets access on the container, not the blob.
  • root is a folder in the container. client takes a ContainerClient you built yourself.

Google Cloud Storage ​

ts
gcs: {
  driver: 'gcs',
  bucket: 'my-bucket',
  projectId: 'my-project',          // optional
  keyFilename: 'service-account.json', // optional
}

Without keyFilename or credentials ({ client_email, private_key }), the SDK uses Application Default Credentials. apiEndpoint points it at an emulator. options holds extra Storage options.

  • url() is https://storage.googleapis.com/<bucket>/<path>, or url plus the path when set.
  • temporaryUrl() is a v4 signed URL, which needs a service account key (or the IAM Credentials API on Cloud Run and GKE). GCS allows up to 7 days.
  • visibility is sent as a predefined ACL (publicRead or private). Buckets with uniform bucket-level access refuse it, so leave it out there.
  • root is a folder in the bucket. client takes a Bucket you built yourself.

Uploads to a disk ​

FileStorage.save() and saveAll() take a disk option, so file uploads go to any disk with the same checks: extension and MIME allowlists, the size limit (enforced while streaming), no overwrite unless asked, and image transforms.

ts
import { Controller, FileStorage, MultipartFile, Post, UploadFile } from '@meghjs/core';

@Controller('/avatars')
export class AvatarController {
  constructor(private readonly files: FileStorage) {}

  @Post()
  upload(@UploadFile('avatar') file: MultipartFile) {
    return this.files.save(file, {
      disk: 's3',
      to: 'avatars',
      allowedMimeTypes: ['image/*'],
      transform: { resize: { width: 256, height: 256 }, format: 'webp' },
    });
  }
}

The result has the file's path on the disk and the disk name, next to the fields it always had:

json
{
  "filename": "3f9c0d0e-....webp",
  "originalFilename": "me.png",
  "size": 9120,
  "path": "avatars/3f9c0d0e-....webp",
  "disk": "s3",
  "uploadPath": "/uploads/avatars/3f9c0d0e-....webp",
  "staticPath": "/static/avatars/3f9c0d0e-....webp"
}

Get a URL for it with storage.disk('s3').url(result.path) or temporaryUrl(result.path, 300).

Where a save goes when it names no disk:

  1. disk set with fileStorage.configure({ disk }).
  2. The default disk, once app.useStorage() was called, unless configure({ baseDir }) was.
  3. Otherwise baseDir (<cwd>/public), as before.

Saving to a local disk uses the same code as baseDir, including the symlink checks.

Presigned URLs ​

temporaryUrl(path, expiresIn) gives a link that works for expiresIn seconds without making the file public. Use it to let a browser download a private file straight from the bucket:

ts
@Get('/invoices/:id')
async download(@Param('id') id: string) {
  const url = await this.storage.disk('s3').temporaryUrl(`invoices/${id}.pdf`, 300);
  return Results.Redirect(url);
}

It doesn't check that the file exists; the link answers 404 if it doesn't.

Testing ​

Storage.fake(name?) replaces a disk (the default one when no name is given) with an in-memory disk, and returns it. It behaves like a real disk and adds assertions:

ts
import { Storage } from '@meghjs/core';

afterEach(() => Storage.restore());

it('stores the avatar', async () => {
  const disk = Storage.fake('s3');

  await avatars.save('42', png);

  disk.assertExists('avatars/42.png');
  disk.assertExists('avatars/42.png', png); // and its content
  disk.assertMissing('avatars/41.png');
});
AssertionPasses when
assertExists(path, content?)A file is at path (with this content, when given)
assertMissing(path)No file is at path
assertCount(n, dir?)There are n files under dir (the whole disk when left out)
assertDirectoryEmpty(dir?)There are no files under dir

A failed assertion throws an error that lists the files on the disk, so it works with any test runner. disk.files holds the files themselves, with their content type and visibility. Storage.restore(name?) undoes one fake, or all of them.

Disks injected with @InjectDisk look the disk up on every call, so a fake made after the service was built still applies. A disk taken with storage.disk('s3') and kept in a field does not: call disk() when you use it, or fake before building the service.

FileStorage uploads go to the fake when they name the disk, or when the app called useStorage() and the fake replaces the default disk.

Released under the MIT License.