Software Crafting

Scaling Secure Document Vaults: Architecting Direct-to-S3 Multipart Uploads and E2E Encryption in Node.js

DDeepak RajputBackend Development10 min read05 Apr 2026Updated 2026-11-07
A dark metal vault-like box with a glowing green core, as streams of green and teal data cubes flow into it from the right

TL;DR: Keep gigabyte-scale file uploads out of your Node.js API by sending them directly to AWS S3. This guide shows how to orchestrate browser multipart uploads with AWS SDK v3 presigned URLs, encrypt objects at rest with SSE-KMS, configure CORS so the browser can read part ETags, and clean up abandoned uploads. SSE-KMS is server-side encryption; if you need true end-to-end encryption, encrypt in the browser before upload, as discussed near the end.

Key Takeaways

  • Avoid OOMKilled pods and long-held connections by removing multer.memoryStorage() and your Express servers from the data path, so file bytes never pass through your Node.js backend.
  • Initialize uploads with CreateMultipartUploadCommand and set encryption at creation by passing ServerSideEncryption: 'aws:kms' with your SSEKMSKeyId, backed by SSE-KMS as the bucket default.
  • Respect S3 multipart limits: every part except the last must be at least 5 MiB, at most 5 GiB, and an upload can have at most 10,000 parts.
  • Issue presigned UploadPartCommand URLs just in time and in small batches, so each URL can have a short expiry and you never hand out thousands of upload grants at once.
  • Keep your Node.js API as a control plane that authorizes uploads and signs URLs with @aws-sdk/s3-request-presigner, rather than a proxy buffering gigabytes of data.

Sending large file uploads through your Node.js API works fine in local development. In production, gigabyte-scale documents expose its limits.

When a user uploads a 5GB video or medical dataset through a buffering middleware, the whole file ends up in process memory, and a few concurrent uploads are enough to get a Kubernetes pod OOMKilled. Even with streaming, each upload ties up a connection, a worker and network bandwidth on your API servers for minutes, slow clients hold that capacity longer, and a deploy or pod restart kills every upload in flight. Your backend ends up acting as an expensive proxy to your storage bucket.

The alternative is to remove Node.js from the data path entirely.

With presigned URLs and S3 multipart upload, clients upload chunks directly to AWS S3 while your API only authorizes and coordinates. We pair this with AWS Key Management Service (KMS) for encryption at rest. In this guide, we will build a resumable, access-controlled upload path for a document vault.

The Anti-Pattern: Memory Exhaustion via Naive Streams

Most Node.js applications handle file uploads using intermediate streams or buffers. Here is a common anti-pattern that breaks down under large files:

import express from 'express';
import multer from 'multer';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const app = express();
// Anti-pattern: Buffering the entire file in memory
const upload = multer({ storage: multer.memoryStorage() });

app.post('/api/upload', upload.single('document'), async (req, res) => {
  const s3 = new S3Client({ region: 'us-east-1' });

  await s3.send(
    new PutObjectCommand({
      Bucket: 'secure-document-vault',
      Key: req.file.originalname,
      Body: req.file.buffer, // The entire file is held in process memory here
    }),
  );

  res.status(200).send('Upload complete');
});

Production Warning: Even if you swap multer.memoryStorage() for multer.diskStorage() and pipe a read stream to S3, every byte still crosses your servers twice, consumes local disk and I/O, and is lost if the pod restarts mid-upload.

For document vaults or media platforms with large files, it is simpler to keep file bytes off your backend entirely.

Phase 1: Initializing the Direct-to-S3 Multipart Vault

We will use the AWS SDK v3 to orchestrate the upload. The Node.js backend acts only as the control plane: it checks that the user may upload, then signs requests that let the browser talk directly to S3.

First, we initialize the multipart upload. This tells S3 to expect an incoming file broken into numbered parts. We set server-side encryption with a customer-managed KMS key at creation; the parts and the final object inherit it.

import { randomUUID } from 'node:crypto';
import { S3Client, CreateMultipartUploadCommand } from '@aws-sdk/client-s3';

const s3Client = new S3Client({ region: process.env.AWS_REGION });

export async function initiateUpload(userId: string, mimeType: string) {
  const command = new CreateMultipartUploadCommand({
    Bucket: process.env.S3_VAULT_BUCKET,
    // Never build keys from user-supplied file names; store the original name in your database
    Key: `uploads/${userId}/${randomUUID()}`,
    ContentType: mimeType,
    // Enforce KMS encryption at the moment of object creation
    ServerSideEncryption: 'aws:kms',
    SSEKMSKeyId: process.env.AWS_KMS_KEY_ID,
  });

  try {
    const { UploadId, Key } = await s3Client.send(command);
    if (!UploadId) throw new Error('Failed to obtain UploadId');

    // Persist { userId, uploadId, objectKey } so later calls can be authorized against it
    return { uploadId: UploadId, objectKey: Key };
  } catch (error) {
    console.error('Multipart init failed:', error);
    throw new Error('Storage initialization failed');
  }
}

Phase 2: Generating Pre-Signed Chunk URLs

AWS S3 has strict rules for multipart uploads:

  1. Every part except the last must be at least 5 MiB, and no part can exceed 5 GiB.
  2. A single upload can have at most 10,000 parts, and the final object at most 48.8 TiB according to the current S3 limits table.

For a 50GB file with 10MB chunks, the client needs 5,000 presigned URLs. Signing is cheap (a few HMAC-SHA256 operations per URL, done locally without calling AWS), so CPU is not the main concern. The problem with issuing all of them up front is exposure and expiry: thousands of live upload grants exist at once, and URLs with a short expiry run out before a slow upload reaches them.

Instead, we expose an endpoint that generates presigned URLs in small batches as the client needs them. Before signing, look up the uploadId in your database and confirm it belongs to the requesting user; otherwise any logged-in user could request URLs for someone else's upload.

import { S3Client, UploadPartCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const s3Client = new S3Client({ region: process.env.AWS_REGION });

interface PresignRequest {
  uploadId: string;
  objectKey: string;
  partNumbers: number[]; // e.g., [1, 2, 3, 4, 5]
}

export async function generatePartUrls(req: PresignRequest) {
  const { uploadId, objectKey, partNumbers } = req;
  const urls: Record<number, string> = {};

  // Callers request small batches; reject large partNumbers arrays at the API layer
  await Promise.all(
    partNumbers.map(async (partNumber) => {
      const command = new UploadPartCommand({
        Bucket: process.env.S3_VAULT_BUCKET,
        Key: objectKey,
        UploadId: uploadId,
        PartNumber: partNumber,
      });

      // URL expires in 15 minutes, limiting how long a leaked URL is useful
      urls[partNumber] = await getSignedUrl(s3Client, command, { expiresIn: 900 });
    }),
  );

  return urls;
}

Tip: Do not request 10,000 URLs in a single API call. Have your frontend request URLs in small batches just in time as the upload progresses, and cap the batch size on the server. The example client below requests one URL per part for clarity.

Phase 3: Client-Side Concurrency and Fault Tolerance

The browser does the heavy lifting with the native File.slice() API. It returns a Blob that refers to a byte range of the file, so the browser reads only the chunk being uploaded instead of the whole file.

The frontend must orchestrate chunking, manage concurrent uploads, and capture the ETags returned by S3 in the response headers. Browsers can only read the ETag header if the bucket's CORS configuration exposes it:

[
  {
    "AllowedOrigins": ["https://app.example.com"],
    "AllowedMethods": ["PUT"],
    "AllowedHeaders": ["*"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3000
  }
]
// browser-client.ts
const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB

interface UploadedPart {
  PartNumber: number;
  ETag: string;
}

export async function uploadFileDirectToS3(file: File) {
  const totalParts = Math.ceil(file.size / CHUNK_SIZE);

  // 1. Initialize Upload via Backend
  const { uploadId, objectKey } = await api.post('/init-upload', {
    fileName: file.name,
    mimeType: file.type,
  });

  const uploadedParts: UploadedPart[] = [];
  const activeUploads = new Set<Promise<void>>();
  const MAX_CONCURRENCY = 4; // Keep a few parts in flight without saturating the connection

  // 2. Upload Orchestration
  for (let i = 0; i < totalParts; i++) {
    // Wait for a slot to open if we've hit our concurrency limit
    if (activeUploads.size >= MAX_CONCURRENCY) {
      await Promise.race(activeUploads);
    }

    const partNumber = i + 1;
    const start = i * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE, file.size);
    const chunk = file.slice(start, end);

    const uploadPromise = (async () => {
      try {
        // Fetch presigned URL just-in-time
        const { url } = await api.post('/get-part-url', { uploadId, objectKey, partNumber });
        const eTag = await uploadChunk(url, chunk, partNumber);

        uploadedParts.push({ PartNumber: partNumber, ETag: eTag });
      } catch (err) {
        console.error(`Chunk ${partNumber} failed`, err);
        // Implementation note: Add retry logic with exponential backoff here
        throw err;
      }
    })();

    activeUploads.add(uploadPromise);
    // Errors surface through Promise.race/Promise.all; the catch only prevents an unhandled rejection
    uploadPromise.finally(() => activeUploads.delete(uploadPromise)).catch(() => {});
  }

  // Wait for all remaining active uploads to finish
  await Promise.all(activeUploads);

  // 3. Complete Upload
  await api.post('/complete-upload', {
    uploadId,
    objectKey,
    parts: uploadedParts.sort((a, b) => a.PartNumber - b.PartNumber), // Parts must be listed in ascending order
  });
}

async function uploadChunk(url: string, chunk: Blob, partNumber: number): Promise<string> {
  const response = await fetch(url, {
    method: 'PUT',
    body: chunk,
  });

  if (!response.ok) throw new Error(`HTTP ${response.status}`);

  // S3 returns the ETag wrapped in quotes; pass it back unchanged.
  const eTag = response.headers.get('ETag');
  if (!eTag) throw new Error('No ETag returned from S3');

  return eTag;
}

Phase 4: Validating ETags and Completing the Vault Entry

Once the frontend finishes uploading chunks, S3 still treats them as isolated, unlinked fragments. If you look in the AWS console, the file does not exist yet.

Your Node.js backend must issue a CompleteMultipartUploadCommand, passing the exact array of PartNumber and ETag combinations. S3 checks that each listed part exists with that ETag, assembles the parts in ascending part-number order, and makes the object available. For end-to-end integrity checks, use S3's additional checksums (for example CRC-64/NVME) rather than relying on ETags. As before, confirm the uploadId belongs to the requesting user before completing it.

import { S3Client, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';

const s3Client = new S3Client({ region: process.env.AWS_REGION });

interface CompleteRequest {
  uploadId: string;
  objectKey: string;
  parts: { PartNumber: number; ETag: string }[];
}

export async function completeUpload(req: CompleteRequest) {
  // Parts must be listed in ascending PartNumber order
  const sortedParts = [...req.parts].sort((a, b) => a.PartNumber - b.PartNumber);

  const command = new CompleteMultipartUploadCommand({
    Bucket: process.env.S3_VAULT_BUCKET,
    Key: req.objectKey,
    UploadId: req.uploadId,
    MultipartUpload: {
      Parts: sortedParts,
    },
  });

  try {
    const response = await s3Client.send(command);
    return { fileUrl: response.Location, eTag: response.ETag };
  } catch (error) {
    console.error('Failed to complete upload stitch:', error);
    // InvalidPart or InvalidPartOrder means the part list does not match what S3 received
    throw new Error('Upload completion failed');
  }
}

Production Note: The ETag returned by a completed multipart upload is not an MD5 hash of the entire file. It typically looks like "hash-N", where N is the number of parts, and with SSE-KMS even single-part ETags are not MD5 digests. Do not validate the final ETag against a local MD5 of the original file; use checksums instead.

Preventing Cost Leaks: Orphaned Multipart Uploads

What happens if a user starts uploading a 100GB dataset, closes their laptop at 50%, and never returns?

S3 keeps those uploaded parts until the upload is completed or aborted, and bills you for their storage even though no object appears in the bucket listing. To prevent this, define an S3 lifecycle rule that aborts incomplete multipart uploads.

Here is a Terraform configuration snippet to enforce this lifecycle rule:

resource "aws_s3_bucket_lifecycle_configuration" "vault_lifecycle" {
  bucket = aws_s3_bucket.secure_vault.id

  rule {
    id     = "abort-incomplete-multipart-uploads"
    status = "Enabled"

    filter {} # applies to the whole bucket

    abort_incomplete_multipart_upload {
      days_after_initiation = 3
    }
  }
}

Without Terraform, you can apply the same rule as a lifecycle configuration with the AWS CLI (aws s3api put-bucket-lifecycle-configuration) or the console, so orphaned parts are removed 3 days after initiation.

Enforcing Encryption and TLS with Bucket and KMS Policies

Finally, every presigned URL is a temporary grant to write to your bucket, so add guardrails at the bucket level as well.

Since January 2023, S3 encrypts every new object with SSE-S3 by default. For a vault, set the bucket's default encryption to SSE-KMS with your customer-managed key and enable S3 Bucket Keys to reduce KMS request costs. Then add a bucket policy that rejects writes asking for a different encryption type and any request made without TLS. The policy uses StringNotEqualsIfExists because UploadPart requests also need s3:PutObject permission but do not carry the encryption header; a plain StringNotEquals would deny them. Test the policy with a real multipart upload before rolling it out.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RequireKMSEncryption",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::secure-document-vault/*",
      "Condition": {
        "StringNotEqualsIfExists": {
          "s3:x-amz-server-side-encryption": "aws:kms"
        }
      }
    },
    {
      "Sid": "EnforceTLSRequestsOnly",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::secure-document-vault", "arn:aws:s3:::secure-document-vault/*"],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    }
  ]
}

Remember that the presigning role also needs kms:GenerateDataKey and kms:Decrypt on the key, because S3 calls KMS on behalf of the requester for multipart uploads with SSE-KMS.

A Note on End-to-End Encryption

SSE-KMS protects data at rest inside AWS, and anyone with s3:GetObject and kms:Decrypt can read the plaintext. If your threat model requires that neither your servers nor AWS can read documents, encrypt each chunk in the browser (for example with AES-GCM through the Web Crypto API) before upload and manage the keys outside AWS. That is a larger design involving key distribution, sharing and recovery, and it is outside the scope of this guide.

By combining browser-side chunking, presigning in the Node.js control plane, KMS encryption, and S3 lifecycle rules, you get an upload path where your backend memory stays flat regardless of file size and upload bandwidth goes straight to S3 instead of through your servers. If you want a team to review or build this for your product, see our backend development and API services.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

Why shouldn't I stream large file uploads directly through my Node.js backend?

Buffering uploads with middleware like Multer's memory storage holds whole files in process memory, which leads to OOMKilled pods, and even streaming ties up API servers and connections for the length of every upload. Letting the backend act only as a control plane keeps file bytes off your servers.

What are the AWS S3 limitations for multipart uploads?

Every part except the last must be at least 5 MiB and at most 5 GiB, a single upload can have at most 10,000 parts, and the final object can be up to 48.8 TiB.

Should I generate all presigned part URLs at the start of an upload?

Usually not. Signing is cheap, but issuing thousands of URLs at once creates many live upload grants and forces long expiry times. Generate URLs in small batches as the client needs them, authorize each request against the stored upload, and keep expiry short.

Which AWS SDK commands are needed to initialize a direct-to-S3 multipart upload?

You need the AWS SDK v3 for Node.js, specifically utilizing the CreateMultipartUploadCommand from @aws-sdk/client-s3. This command tells S3 to expect an incoming file broken into numbered parts and returns the UploadId required for generating subsequent chunk URLs.

About the author

Deepak Rajput

Founder and CEO of SoftwareCrafting

Deepak Rajput is the Founder and CEO of SoftwareCrafting in Delhi and writes about web, mobile, backend, cloud, security, and engineering leadership.

Writes about Next.js, Node.js, React Native, PostgreSQL, AWS, Kubernetes.

View author profile

Last updated: 2026-11-07