User uploads on Amazon S3

Store files on Amazon S3 and let signed-in users upload avatars through an HTTP function that checks their token.

Storage endpoints accept identities and API keys, not users. To let end users upload files, accept the upload in a function that checks the user's token and stores the file with an API key. This recipe stores avatars on S3 and saves their URL in a Profiles bucket.

1. Store files on S3

Start the API with the S3 strategy:

Terminal
--storage-strategy=awss3 \
--awss3-bucket-name=acme-spica-media

Credentials come from the AWS default credential chain (environment variables, an EKS service account role or an instance profile), or from a JSON file passed with --awss3-credentials-path. The identity needs s3:PutObject, s3:GetObject and s3:DeleteObject on the bucket.

Object URLs then point to S3 directly, for example https://acme-spica-media.s3.eu-central-1.amazonaws.com/avatars/<userId>-1795889886000.png. To serve avatars publicly, allow public reads on the avatars/ prefix with a bucket policy, or put CloudFront in front of the bucket.

2. The profile bucket

bucket/Profiles/schema.yaml
title: Profiles
description: Public profile of each user
primary: name
properties:
  user:
    type: string
    title: User id
  name:
    type: string
    title: Name
  avatar:
    type: storage
    title: Avatar
indexes:
  - definition: {user: 1}
    options: {unique: true}

3. The upload function

Store an API key with StorageFullAccess and data access to Profiles as the secret SPICA_API_KEY, and the bucket id as PROFILES_BUCKET_ID.

function/avatar/schema.yaml
name: avatar
description: Uploads the caller's avatar
language: javascript
timeout: 30
triggers:
  upload:
    type: http
    active: true
    options:
      method: Post
      path: /me/avatar
      authenticate: [USER]
      rateLimit: {limit: 10, ttl: 60000}
function/avatar/index.mjs
import * as Auth from "@spica-devkit/auth";
import * as Bucket from "@spica-devkit/bucket";
import * as Storage from "@spica-devkit/storage";

Auth.initialize({apikey: process.env.SPICA_API_KEY});
Bucket.initialize({apikey: process.env.SPICA_API_KEY});
Storage.initialize({apikey: process.env.SPICA_API_KEY});

const TYPES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"};
const MAX_BYTES = 2 * 1024 * 1024;

export async function upload(req, res) {
  const token = (req.headers.get("authorization") ?? "").replace(/^USER /, "");
  const user = await Auth.verifyToken(token);

  const {contentType, data} = req.body ?? {};
  const extension = TYPES[contentType];
  const content = data ? Buffer.from(data, "base64") : undefined;

  if (!extension || !content || content.length > MAX_BYTES) {
    return res.status(400).send({message: "Send a PNG, JPEG or WebP image up to 2 MB as base64."});
  }

  const object = await Storage.insert({
    name: `avatars/${user._id}-${Date.now()}.${extension}`,
    contentType,
    data: content
  });

  const [profile] = await Bucket.data.getAll(process.env.PROFILES_BUCKET_ID, {
    queryParams: {filter: `document.user == "${user._id}"`, limit: 1}
  });
  if (profile) {
    await Bucket.data.patch(process.env.PROFILES_BUCKET_ID, profile._id, {avatar: object.url});
  } else {
    await Bucket.data.insert(process.env.PROFILES_BUCKET_ID, {user: user._id, name: user.username, avatar: object.url});
  }

  return {url: object.url};
}

Install @spica-devkit/auth, @spica-devkit/bucket and @spica-devkit/storage as dependencies of the function.

4. Upload from the app

JavaScript
async function uploadAvatar(file, token) {
  const data = btoa(String.fromCharCode(...new Uint8Array(await file.arrayBuffer())));
  const response = await fetch("https://api.example.com/api/fn-execute/me/avatar", {
    method: "POST",
    headers: {Authorization: `USER ${token}`, "Content-Type": "application/json"},
    body: JSON.stringify({contentType: file.type, data})
  });
  return (await response.json()).url;
}

Notes

  • Request bodies are limited by --payload-size-limit (15 MiB by default), and base64 adds about a third to the size. For large files, use resumable uploads from a trusted backend instead.
  • Validate the content type and size in the function. The storage API accepts any file.
  • Object names are unique: inserting an existing name fails with An object with this name already exists. The function adds a timestamp to every upload, which also busts caches. Delete the previous avatar with Storage.remove if you don't want to keep it.