Going further

Assets

Uploaded images, video, audio and PDFs: a blob store beside the content store, and fields that point at files.

Documents and files are kept apart. A content store keeps documents (JSON files, a database); a blob store keeps the bytes of uploaded files (a folder, a bucket). Pick each on its own: JSON files with S3, or a database with a folder. createContent takes both and applies the rules.

import { createContent } from '@mortar-kit/core';
import { createFileBlobStore, createJsonFileStore } from '@mortar-kit/core/server';

const content = createContent({
  store: createJsonFileStore({ dir: 'content' }),
  blobs: createFileBlobStore({ dir: 'uploads', baseUrl: '/uploads/' }),
  collections,
  bricks,
});

With a blob store, content.assets has list, upload, remove, update and the folder methods, and the admin shows its asset library.

Keys

An uploaded file is stored under a key made from its name: Hero Photo.png becomes hero-photo-x7k2q9.png. The six random characters keep two uploads of the same name apart, and the extension says what the file is. A blob store only has to list its files, which any folder or bucket can do.

The rules

content.assets, whatever the blob store:

  • checks the type by extension: images (JPEG, PNG, GIF, WebP, AVIF), video (MP4, WebM, MOV), audio (MP3, M4A, Ogg, WAV) and PDF. SVG is refused, since it can carry script and uploads are served from your own origin;
  • checks the size, 25 MB by default (maxAssetSize);
  • returns problems ({ ok: false, message }) instead of throwing;
  • refuses to delete a file while documents use it, and returns those documents, as for references.

Fields that point at files

fields.image stores { src, alt, title, asset } and fields.file({ accept }) stores { src, title, asset }. For an upload, asset is the key, and createContent stores src empty and fills it in from blobs.url(asset) on every read. So bricks render src and nothing else, and moving files to a CDN only changes url. A plain URL still works: asset is then ''.

const video = defineBrick({
  name: 'video',
  schema: { video: fields.file({ label: 'Video', accept: ['video'], required: true }) },
  component: (props) => <video src={props.data.video.src} controls />,
});

Titles, alt text and folders

Editors can give each file a default title and, for images, default alt text, and put files in folders. Picking a file for an image or file field copies its defaults into the field (where the file has them; otherwise what was typed stays), and the field can still be edited. The library searches names, titles and alt text, and uploads go into the folder being shown, several files at once.

const folder = await content.assets.saveFolder({ name: 'Products' }); // { ok, folder: { id, name } }
await content.assets.upload(file, { folder: folder.id });
await content.assets.update(key, { title: 'Red mug', alt: 'A red enamel mug on a table' });
await content.assets.removeFolder(folder.id); // its files stay, in no folder

These details live in the content store, not the blob store: one document, mortar-assets/library (with JSON files, content/mortar-assets/library.json), so every blob store gets them with no change and there's nothing to migrate. Files without details simply have none. The collection name mortar-assets is reserved.

Folders are one level deep, and a file's folder is a detail, so moving a file never changes its key or breaks a document that uses it.

Serving files

A folder isn't public by itself. serveBlob(blobs, key, request) answers a request for one file: its type from the key, nosniff, a long cache (keys never change content) and byte ranges, so video can seek. createMiddleware({ auth, blobs }) from @mortar-kit/auth does it for you, at the path blobs.url('') gives (see Sign-in). Or mount it on a route or a middleware of your own:

// src/middleware.ts (start.middleware)
import { serveBlob } from '@mortar-kit/core';

export default (event, next) => {
  const path = new URL(event.request.url).pathname;
  if (event.request.method === 'GET' && path.startsWith('/uploads/')) {
    return serveBlob(blobs, path.slice('/uploads/'.length), event.request);
  }
  return next();
};

Uploads reach the server through createContentServer's uploadAsset (see Storage). contentClient sends each file as a single FormData (file, plus folder, title, alt when given), since a server function encodes a lone FormData natively but not a file beside other arguments. Server functions accept 1 MiB by default; createContentServer raises that limit to fit createContent's maxAssetSize (25 MB unless you set it), so the limit is set in one place. Import the module that calls it from your serverFunctions.serverSetup module, so the limit is in place before the first upload.

Writing a blob store

A blob store is five methods. Keep it dumb: createContent checks types, sizes and keys before calling it.

interface BlobStore {
  list(): Promise<{ key: string; size: number; modified?: string }[]>;
  get(key: string): Promise<Blob | undefined>;
  put(key: string, data: Blob): Promise<void>;
  remove(key: string): Promise<void>;
  url(key: string): string;
}

url is synchronous: it's computed, not looked up. For S3 it's the bucket's or CDN's URL plus the key; for a folder, the path you serve it at.

Blob store Where Use
createFileBlobStore({ dir, baseUrl? }) @mortar-kit/core/server One file per asset in a folder. Writes are atomic.
createMemoryBlobStore({ baseUrl? }) @mortar-kit/core In memory: tests and demos.

BlobStoreinterface

import { BlobStore } from '@mortar-kit/core'

interface BlobStore

Where uploaded files live: bytes by key. Implement it to keep files anywhere (a folder, S3, a CDN). Deliberately dumb; createContent checks types, sizes and keys, and refuses to delete a file documents use.

Properties

list: () => Promise<BlobInfo[]>

Every stored file. [] if none.

get: (key: string) => Promise<Blob | undefined>

The file under key (its type set from the key's extension), or undefined.

put: (key: string, data: Blob) => Promise<void>

Stores data under key, replacing any file there.

remove: (key: string) => Promise<void>

Removes the file under key; nothing happens if there is none.

url: (key: string) => string

The URL the site loads the file from, e.g. /uploads/<key> or a bucket URL. Synchronous: it is computed, never looked up.

Assetsinterface

import { Assets } from '@mortar-kit/core'

interface Assets

Uploaded files: what the admin's library and pickers need. The methods marked optional are always there from createContent; an app wrapping them (in server functions) may leave them out, and the admin then hides what needs them (details, folders).

Properties

readonly maxSize?: number

The largest file upload accepts, in bytes (createContent's maxAssetSize).

list: () => Promise<Asset[]>

Every uploaded file, newest first.

upload: (file: File, details?: AssetDetails) => Promise<UploadResult>

Checks a file (type by its name's extension, size) and stores it under a fresh key, with details (e.g. the folder to put it in). Problems are returned, not thrown.

remove: (key: string) => Promise<RemoveResult>

Deletes a file by key, unless documents use it (then they are returned). Its details go with it.

update?: (key: string, details: AssetDetails) => Promise<UpdateAssetResult>

Sets a file's default title, alt text or folder. Problems are returned, not thrown.

folders?: () => Promise<AssetFolder[]>

Every folder, by name.

saveFolder?: (folder: { id?: string; name: string }) => Promise<FolderResult>

Creates a folder (no id) or renames one. Names are unique, ignoring case.

removeFolder?: (id: string) => Promise<void>

Deletes a folder; its files stay, in no folder.

serveBlobfunction

import { serveBlob } from '@mortar-kit/core'

function serveBlob(store: BlobStore, key: string, request?: Request): Promise<Response>

A response serving one stored file: for an app route or middleware such as /uploads/*. Types come from the key's extension and are sent with nosniff, so a file can't be read as anything else; keys never change content, so files are cached for good. Answers byte ranges (video seeking) and 404 for an invalid key or a missing file.

Parameters

store: BlobStore
key: string
request?: Request

Returns

Promise<Response>

Assetinterface

import { Asset } from '@mortar-kit/core'

interface Asset

An uploaded file, as Assets.list returns it.

Properties

key: string

The key documents store, e.g. hero-photo-x7k2q9.jpg.

name: string

The name it was uploaded as, lowercased (hero-photo.jpg).

kind: AssetKind
type: string

MIME type, from the extension.

size: number

Size in bytes.

src: string

URL to load it from (BlobStore.url).

modified?: string

When it was stored (ISO 8601), if the store knows.

title: string

Default title: copied into an image or file field when the asset is picked. '' if none.

alt: string

Default alt text (images): copied into an image field when the asset is picked. '' if none.

folder: string

The id of the folder it is in, or '' for none.

AssetDetailsinterface

import { AssetDetails } from '@mortar-kit/core'

interface AssetDetails

What editors set on an asset. Each part left out stays as it is.

Properties

title?: string

Default title, at most 200 characters.

alt?: string

Default alt text, at most 1000 characters.

folder?: string

A folder id, or '' for none.