How to store your app's files with upload and download links
Updated
Each Kaiva Cloud database comes with its own file storage. Your app's server asks the Storage API for an upload or download link that works for 15 minutes, sends the file with it, and keeps the file's path in a table. The storage key stays on your server, and files never pass through Kaiva.
With Kaiva Cloud
Every database has its own storage, on its Files tab in the Kaiva Cloud console, where you can also upload files by hand. Create a storage key there and keep it on your app's server: it is shown once, and a new key replaces the old one, which stops working at once. Files are stored in the EU.
Use the links from your server's code: a visitor's browser sends the file to your server, which uploads it. The steps below are the same setup with a bucket of your own.
Step by step
- Create a private bucketAt Amazon S3, Cloudflare R2, Google Cloud Storage or any S3-compatible store. Keep it private: every file is reached through a link your server signs.
- Give your server a keyMake an access key that can only read and write that bucket, and put it in your server's environment. It never goes to a browser.
- Choose the path on the serverBuild each path from the owner and a random part, such as photos/<user id>/<random>.jpg, rather than from the name the file arrived with.
- Sign an upload link and send the fileSign a PUT link for that path that expires in minutes, and send the bytes with it. The content type you send must match the one you signed.
- Save the path, sign downloadsAdd a row with the path, the owner and the size. When someone asks for the file, check the row is theirs, then sign a short-lived GET link.
The Storage API from your server
Send the storage key as Authorization: Bearer. An upload link takes exactly the size you asked for, and a download link hands the file over as a download.
import fs from 'node:fs/promises';
const API = 'https://api.kaiv.ai/api/cloud/v1/storage';
const auth = { Authorization: `Bearer ${process.env.KAIVA_STORAGE_KEY}` };
const file = await fs.readFile('avatar.jpg');
// 1. Ask for an upload link for the file's exact size.
const res = await fetch(`${API}/upload`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify({ path: 'photos/ada/avatar.jpg', size: file.length }),
});
const { url } = await res.json();
// 2. Send the file straight to storage.
await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/octet-stream' },
body: file,
});Every Storage API call
Each call takes the storage key, and each reaches only its own database's files.
| Call | What it does |
|---|---|
| POST /upload { path, size } | A link to upload exactly that many bytes to the path |
| POST /download { path } | A link to download the file |
| GET /files?prefix= | The files under a path, up to 200 |
| DELETE /files?path= | Removes one file |
An upload link in Node.js
With the AWS SDK, which works with S3 and with R2 (give it R2's endpoint and the region auto). This link works for 15 minutes.
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const s3 = new S3Client({ region: 'eu-central-1' });
const path = `photos/${userId}/${crypto.randomUUID()}.jpg`;
const url = await getSignedUrl(
s3,
new PutObjectCommand({
Bucket: 'my-app-files',
Key: path,
ContentType: 'image/jpeg',
}),
{ expiresIn: 900 },
);Keep the path in Postgres
The table is where your app lists a person's files and checks who may download one. The bucket holds only the bytes.
create table files (
id bigint generated always as identity primary key,
user_id text not null,
path text not null unique,
size bigint not null,
created_at timestamptz not null default now()
);Uploads from the browser
Either the browser sends the file to your server, which uploads it with the link, or the browser asks your server for the link and uploads the file itself. The second keeps large files off your server, and needs a CORS rule on the bucket that allows PUT from your site's address.
Other ways to do it
- Your host's storageSupabase Storage and Firebase Storage come with their own sign-in, so their rules can name the signed-in user.
- Files in the databasePostgres can hold small files in a bytea column. Backups and queries grow with them, so large files belong in storage.
Questions
- How long should a link work?
- Minutes: long enough for the upload or download to start. Sign a new one each time a file is asked for.
- Should I keep a file's link in the database?
- Keep the path, not the link. Links expire; with the path, your server can sign a new link whenever the file is asked for.
- Why does my browser upload fail with a CORS error?
- The bucket does not allow your site. Add a CORS rule for your site's address that allows PUT, and send the same Content-Type the link was signed with.
- Where are the files stored?
- In the EU, with the database they belong to.
- Can a browser hold the storage key?
- No. It is for your server's code. If it ever reaches a browser, make a new key on the Files tab: the old one stops working at once.