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.
| Driver | Stores files in | Needs |
|---|---|---|
local | A folder on the server | Nothing |
s3 | Amazon S3, or an S3-compatible service | @aws-sdk/client-s3, @aws-sdk/s3-request-presigner |
azure | Azure Blob Storage | @azure/storage-blob |
gcs | Google Cloud Storage | @google-cloud/storage |
The cloud SDKs are optional peer dependencies. Install the one you use:
npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
npm i @azure/storage-blob
npm i @google-cloud/storageUsing 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():
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:
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'),
},
},
};
}
}app.useStorage(StorageSettings);Using a disk
Inject Storage and pick a disk with disk(name?):
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:
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
| Method | Does |
|---|---|
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
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()needsurl. Serve the folder yourself, for example withapp.useStaticFiles({ root: path.join(process.cwd(), 'storage'), prefix: '/storage/' }).temporaryUrl()throws unless you give asigner: a function that returns the URL, for example a route of your app that checks a signature.visibilityandcontentTypeare ignored.
S3
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()ishttps://<bucket>.s3.<region>.amazonaws.com/<path>, orurlplus the path when set. The object must be public for that URL to work.temporaryUrl()is a presignedGetObjectURL. S3 allows up to 7 days.visibilityis sent as an ACL (public-readorprivate). Buckets created since 2023 have ACLs turned off and refuse them, so only set it when your bucket uses ACLs. Withoutvisibility, 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.
clienttakes anS3Clientyou 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:
| Service | Settings |
|---|---|
| Cloudflare R2 | endpoint: 'https://<account-id>.r2.cloudflarestorage.com', region: 'auto' |
| MinIO | endpoint: 'http://localhost:9000', region: 'us-east-1', forcePathStyle: true |
| DigitalOcean Spaces | endpoint: 'https://<region>.digitaloceanspaces.com', region: '<region>' (e.g. nyc3) |
| Backblaze B2 | endpoint: 'https://s3.<region>.backblazeb2.com', region: '<region>' (e.g. us-west-004) |
| Wasabi | endpoint: 'https://s3.<region>.wasabisys.com', region: '<region>' (e.g. eu-central-1) |
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
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, orurlplus 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.visibilityis ignored: Azure sets access on the container, not the blob.rootis a folder in the container.clienttakes aContainerClientyou built yourself.
Google Cloud Storage
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()ishttps://storage.googleapis.com/<bucket>/<path>, orurlplus 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.visibilityis sent as a predefined ACL (publicReadorprivate). Buckets with uniform bucket-level access refuse it, so leave it out there.rootis a folder in the bucket.clienttakes aBucketyou 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.
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:
{
"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:
diskset withfileStorage.configure({ disk }).- The default disk, once
app.useStorage()was called, unlessconfigure({ baseDir })was. - 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:
@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:
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');
});| Assertion | Passes 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.