Published
The problem with a public key
Browser uploads use your public key, and a public key is visible to anyone who views the page source. Allowed origins stop other websites from using it, but anyone on your own site can still upload, signed in or not.
To decide who may upload, your server gives each signed-in user a short-lived upload token. The browser sends it with the upload, and Fileboy marks the file signed: true.
1. A token endpoint on your server
The endpoint needs your private key, so it lives on the server. It checks who is asking, then returns a token that works for 60 seconds and only allows uploads. In Express:
import express from "express"
import { Fileboy } from "@cd2/fileboy-node"
const fileboy = Fileboy({
publicKey: process.env.FILEBOY_PUBLIC_KEY!,
privateKey: process.env.FILEBOY_PRIVATE_KEY!,
})
const app = express()
app.use(express.json()) // the JSON bodies below (req.body.fileId) need it
app.post("/api/fileboy/token", (req, res) => {
if (!req.user) return res.status(401).json({ error: "Sign in to upload files" }) // your own auth
const token = fileboy.createAccessToken({ upload: true, expiresInSeconds: 60 })
res.json({ token })
})In the Next.js App Router, @cd2/fileboy-next has this as a route handler, with authorize required so the endpoint can't be left open:
import { createUploadTokenHandler } from "@cd2/fileboy-next"
import { auth } from "@/auth"
export const runtime = "nodejs"
export const POST = createUploadTokenHandler({
authorize: async () => !!(await auth())?.user,
})2. Point the uploader at it
Give the provider the URL instead of a token. The uploader asks it for a fresh token before each upload, with a POST, and expects { "token": "..." } back.
import { FileboyProvider, FileUploader } from "@cd2/fileboy-react"
<FileboyProvider publicKey="YOUR_PUBLIC_KEY" uploadToken="/api/fileboy/token">
<FileUploader allow="image/*" />
</FileboyProvider>app.use(
createFileboy({ publicKey: "YOUR_PUBLIC_KEY", uploadToken: "/api/fileboy/token" }),
)3. Check the file is signed before you save it
A token does not turn the public key off: someone could still upload a file with the key alone, and send you its ID. So when the browser tells your server which file to save, check that it was uploaded with a token:
app.post("/api/avatar", async (req, res) => {
const file = await fileboy.fetchFileData(req.body.fileId)
if (!file.signed) return res.status(400).json({ error: "Upload with a signed-in session" })
// save file.id against req.user here
res.json({ ok: true })
})A token proves a signed-in user uploaded the file, not that the file is safe. Keep virus scanning on, and limit what the uploader accepts with allow.
Checked against the current libraries in November 2026. Found something that no longer works? Tell us.