Published
What you are building
A form posts to an Astro endpoint. The endpoint reads the file and sends it to Fileboy. Endpoints that read a request body run on demand, so the project needs a server adapter, or output: "server".
1. Install and set your keys
npm install @cd2/fileboy-nodeimport { Fileboy } from "@cd2/fileboy-node"
export const fileboy = Fileboy({
publicKey: import.meta.env.FILEBOY_PUBLIC_KEY!,
privateKey: import.meta.env.FILEBOY_PRIVATE_KEY, // optional
})FILEBOY_PUBLIC_KEY=your_public_keyYou need a public key. Create a free app and copy it from the Keys page. Keep keys in environment variables, and never put a private key in code that reaches the browser. An upload needs only the public key; add the private key only if your app uses signed requests.
2. Upload the file
import type { APIRoute } from "astro"
import { fileboy } from "../../lib/fileboy"
export const prerender = false
export const POST: APIRoute = async ({ request }) => {
const form = await request.formData()
const file = form.get("avatar")
if (!(file instanceof File) || file.size === 0) {
return Response.json({ error: "Choose a file" }, { status: 400 })
}
try {
const uploaded = await fileboy.uploadFile(file)
// save uploaded.id against the user here
return Response.json({ id: uploaded.id })
} catch (e) {
const error = e instanceof Error ? e.message : "The upload failed"
return Response.json({ error }, { status: 502 })
}
}---
export const prerender = true
---
<form id="avatar-form">
<input type="file" name="avatar" accept="image/*" required />
<button>Upload</button>
<p id="result"></p>
</form>
<script>
const form = document.querySelector<HTMLFormElement>("#avatar-form")!
const result = document.querySelector("#result")!
form.addEventListener("submit", async event => {
event.preventDefault()
const response = await fetch("/api/avatar", { method: "POST", body: new FormData(form) })
const data = await response.json()
result.textContent = data.id ? "Saved as " + data.id : data.error
})
</script>Store the id the upload returns and nothing else: it is the only thing you need to show the file again, at any size.
3. Show it at the size you need
---
import { fileboy } from "../lib/fileboy"
const id = "THE_STORED_ID"
const src = fileboy.buildImageUrl(id, {
public: true, // no 10-second private-key token in a URL that goes into a page
transforms: [
{ type: "resize", width: 192, height: 192, fit: "cover" },
{ type: "format", format: "webp" },
],
})
---
<img src={src} width="96" height="96" alt="Your avatar" />Reading a file or image needs no key, so these URLs work in <img> tags, emails and anywhere else, unless the app requires signed URLs.
Checked against the current libraries in November 2026. Found something that no longer works? Tell us.