01

Setup

Add your API key and create a base fetch helper. The key is server-side only — never expose it to the browser.

.env.local
1XFILES_API_KEY=xf_AbC12dEfGhIjKlMnOpQrStUvWxYz9012
2NEXT_PUBLIC_XFILES_URL=https://www.xfiles.dev
lib/xfiles.ts
1const API_KEY = process.env.XFILES_API_KEY!;
2const BASE_URL = process.env.NEXT_PUBLIC_XFILES_URL!;
3
4export async function xfiles(path: string, options: RequestInit = {}) {
5 const res = await fetch(`${BASE_URL}${path}`, {
6 ...options,
7 headers: {
8 Authorization: `Bearer ${API_KEY}`,
9 "Content-Type": "application/json",
10 ...options.headers,
11 },
12 });
13 if (!res.ok) {
14 const error = await res.json().catch(() => ({}));
15 throw new Error(error.error || `XFiles API error: ${res.status}`);
16 }
17 return res.json();
18}
02

File Service

One service file. Upload, get, list, delete. Import this in your API routes.

lib/file-service.ts7 responses
1import { xfiles } from "@/lib/xfiles";
2
3// ── Upload ──────────────────────────────────────────────
4// position: controls display order (0 = primary image)
5export async function uploadFile(
6 file: File,
7 entity: { type: string; id: string; role: string; position?: number },
8 opts?: { visibility?: "public" | "private"; transforms?: { enabled: boolean; visibility?: "public" | "private" } },
9) {
10 const intent = await xfiles("/api/v1/files/upload-intent", {
Response
{
"fileId": "abc123def456",
"uploadUrl": "https://s3.amazonaws.com/...?X-Amz-Signature=...",
"key": "files/originals/public/proj_id/abc123/sneaker-k9x2m7.jpg",
"expiresIn": 900
}
11 method: "POST",
12 body: JSON.stringify({
13 filename: file.name,
14 contentType: file.type,
15 size: file.size,
16 visibility: opts?.visibility ?? "private",
17 entity,
18 ...(opts?.transforms && {
19 transformations: { image: opts.transforms },
20 }),
21 }),
22 });
23
24 await fetch(intent.uploadUrl, {
25 method: "PUT",
26 headers: { "Content-Type": file.type },
27 body: file,
28 });
29
30 const { file: confirmed } = await xfiles("/api/v1/files/confirm", {
Response
{
"file": {
"id": "abc123def456",
"filename": "sneaker-front-k9x2m7.jpg",
"originalFilename": "sneaker-front.jpg",
"contentType": "image/jpeg",
"size": 204800,
"visibility": "public",
"uploadStatus": "confirmed",
"ownerUserId": "user_123",
"entity": {
"type": "product",
"id": "prod_abc123",
"role": "gallery",
"position": 0
},
"transformations": {
"image": { "enabled": true, "visibility": "public" }
}
}
}
31 method: "POST",
32 body: JSON.stringify({ fileId: intent.fileId }),
33 });
34 return confirmed;
35}
36
37// ── Refresh ONE file's URLs (only needed to re-sign an expired PRIVATE
38// signed URL — the list/get endpoints already return URLs inline) ──
39export async function getFile(fileId: string) {
Response
{
"file": { "id": "abc123def456", "visibility": "public", "entity": { ... }, ... },
"url": "https://cdn.example.com/originals/public/.../sneaker-front-k9x2m7.jpg",
"variants": [
{ "width": 100, "url": "https://cdn.example.com/.../sneaker-front-k9x2m7_w100.webp" },
{ "width": 300, "url": "..." },
{ "width": 400, "url": "..." },
{ "width": 600, "url": "..." },
{ "width": 800, "url": "..." },
{ "width": 1000, "url": "..." },
{ "width": 1200, "url": "..." }
]
}
40 return xfiles(`/api/v1/files/${fileId}`);
41}
42
43// ── List by entity — sorted by position ─────────────────
44// List all files, or filter by entity / visibility / owner
45export async function listFiles(opts?: {
46 entityType?: string;
47 entityId?: string;
48 role?: string;
49 visibility?: string;
50 ownerUserId?: string;
51 page?: number;
52}) {
53 const params = new URLSearchParams();
54 if (opts?.entityType) params.set("entityType", opts.entityType);
55 if (opts?.entityId) params.set("entityId", opts.entityId);
56 if (opts?.role) params.set("role", opts.role);
57 if (opts?.visibility) params.set("visibility", opts.visibility);
58 if (opts?.ownerUserId) params.set("ownerUserId", opts.ownerUserId);
59 if (opts?.page) params.set("page", String(opts.page));
60 const query = params.toString();
Response
{
"files": [
{
"id": "abc123def456",
"filename": "sneaker-front-k9x2m7.jpg",
"visibility": "public",
"entity": { "type": "product", "id": "prod_abc123", "role": "gallery", "position": 0 },
"transformations": { "image": { "enabled": true, "visibility": "public" } }
}
],
"total": 42,
"page": 1,
"totalPages": 3
}
61 return xfiles(`/api/v1/files${query ? `?${query}` : ""}`);
62}
63
64// ── Update position ─────────────────────────────────────
65export async function updateFilePosition(fileId: string, position: number) {
Response
{
"file": {
"id": "abc123def456",
"visibility": "public",
"entity": { "type": "product", "id": "prod_abc123", "role": "gallery", "position": 2 },
"transformations": { "image": { "enabled": true, "visibility": "public" } }
}
}
66 return xfiles(`/api/v1/files/${fileId}`, {
67 method: "PATCH",
68 body: JSON.stringify({ position }),
69 });
70}
71
72// ── Delete single file ──────────────────────────────────
73export async function deleteFile(fileId: string) {
Response
{ "success": true }
74 return xfiles(`/api/v1/files/${fileId}`, { method: "DELETE" });
75}
76
77// ── Delete all files by entity ──────────────────────────
78// e.g. deleteByEntity("product", "prod_123") deletes all files for that product
79export async function deleteByEntity(entityType: string, entityId: string) {
80 const params = new URLSearchParams({ entityType, entityId });
Response
{ "deleted": 5 }
81 return xfiles(`/api/v1/files?${params}`, { method: "DELETE" });
82}

Note: Call listFiles() with no arguments to get all files (20 per page). Add filters to narrow results. When filtering by entity, results are sorted by position ascending.

03

Real-World Example

An e-commerce product with gallery images. Each image has a position — position 0 is the thumbnail shown in listing pages. Full CRUD.

Entity mapping

type: "product"   id: product.id   role: "gallery"   position: 0, 1, 2...

app/api/products/route.ts — Create & List
1import { NextResponse } from "next/server";
2import { db } from "@/lib/db";
3import { products } from "@/lib/db/schema";
4import { uploadFile, listFiles } from "@/lib/file-service";
5import { desc } from "drizzle-orm";
6
7// POST /api/products — Create product with images
8export async function POST(req: Request) {
9 const formData = await req.formData();
10 const name = formData.get("name") as string;
11 const price = Number(formData.get("price"));
12 const images = formData.getAll("images") as File[];
13
14 const [product] = await db
15 .insert(products)
16 .values({ name, price })
17 .returning();
18
19 // Upload images with position — first image (position 0) is the thumbnail
20 const uploaded = await Promise.all(
21 images.map((file, i) =>
22 uploadFile(
23 file,
24 { type: "product", id: product.id, role: "gallery", position: i },
25 { visibility: "public", transforms: { enabled: true, visibility: "public" } },
26 ),
27 ),
28 );
29
30 return NextResponse.json({ product, images: uploaded });
31}
32
33// GET /api/products — List products with thumbnail (position 0)
34export async function GET() {
35 const allProducts = await db
36 .select()
37 .from(products)
38 .orderBy(desc(products.createdAt));
39
40 const result = await Promise.all(
41 allProducts.map(async (product) => {
42 // One call — each file already carries url + variants inline, so there's NO
43 // per-file lookup. (Better still: cache the gallery on the product row and
44 // skip XFiles on reads entirely — see "Caching" in the API reference.)
45 const { files } = await listFiles({
46 entityType: "product",
47 entityId: product.id,
48 role: "gallery",
49 });
50
51 const thumb = files[0] ?? null;
52 // Pick the 400w variant for listing cards; fall back to the original.
53 const thumbnailUrl =
54 thumb?.variants?.find((v: any) => v.width === 400)?.url ?? thumb?.url ?? null;
55
56 return { ...product, thumbnailUrl };
57 }),
58 );
59
60 return NextResponse.json({ products: result });
61}
app/api/products/[id]/route.ts — Get, Update & Delete
1import { NextResponse } from "next/server";
2import { db } from "@/lib/db";
3import { products } from "@/lib/db/schema";
4import { eq } from "drizzle-orm";
5import { listFiles, uploadFile, deleteFile, deleteByEntity, updateFilePosition } from "@/lib/file-service";
6
7type Params = { params: Promise<{ id: string }> };
8
9// GET /api/products/:id — Product with all gallery images (sorted by position)
10export async function GET(_req: Request, { params }: Params) {
11 const { id } = await params;
12 const [product] = await db.select().from(products).where(eq(products.id, id));
13 if (!product) return NextResponse.json({ error: "Not found" }, { status: 404 });
14
15 // One call. Files come back sorted by position (0 = primary) and each already
16 // includes url + variants[] — no per-file lookup needed.
17 const { files: images } = await listFiles({
18 entityType: "product",
19 entityId: id,
20 role: "gallery",
21 });
22
23 return NextResponse.json({ product, images });
24}
25
26// PATCH /api/products/:id — Update product, add images, reorder
27export async function PATCH(req: Request, { params }: Params) {
28 const { id } = await params;
29 const formData = await req.formData();
30 const name = formData.get("name") as string | null;
31 const price = formData.get("price");
32 const newImages = formData.getAll("images") as File[];
33 const reorder = formData.get("reorder"); // JSON: [{ fileId, position }]
34
35 // Update product fields
36 const updates: Record<string, unknown> = {};
37 if (name) updates.name = name;
38 if (price) updates.price = Number(price);
39 if (Object.keys(updates).length > 0) {
40 await db.update(products).set(updates).where(eq(products.id, id));
41 }
42
43 // Add new images — position after existing ones
44 if (newImages.length > 0) {
45 const { files: existing } = await listFiles({
46 entityType: "product",
47 entityId: id,
48 role: "gallery",
49 });
50 const nextPosition = existing.length;
51
52 await Promise.all(
53 newImages.map((file, i) =>
54 uploadFile(
55 file,
56 { type: "product", id, role: "gallery", position: nextPosition + i },
57 { visibility: "public", transforms: { enabled: true, visibility: "public" } },
58 ),
59 ),
60 );
61 }
62
63 // Reorder images
64 if (reorder) {
65 const order = JSON.parse(reorder as string) as { fileId: string; position: number }[];
66 await Promise.all(order.map((o) => updateFilePosition(o.fileId, o.position)));
67 }
68
69 const [updated] = await db.select().from(products).where(eq(products.id, id));
70 return NextResponse.json({ product: updated });
71}
72
73// DELETE /api/products/:id — Delete product and all its images
74export async function DELETE(_req: Request, { params }: Params) {
75 const { id } = await params;
76
77 // One call deletes all files attached to this product
78 await deleteByEntity("product", id);
79
80 await db.delete(products).where(eq(products.id, id));
81 return NextResponse.json({ success: true });
82}
components/ProductCard.tsx — Display thumbnail
1import Image from "next/image";
2
3// Product listing card — uses the thumbnail URL from the list endpoint
4export function ProductCard({ product }: { product: any }) {
5 return (
6 <article>
7 {product.thumbnailUrl ? (
8 <Image src={product.thumbnailUrl} alt={product.name} width={400} height={300} unoptimized />
9 ) : (
10 <div className="w-full h-48 bg-gray-100 flex items-center justify-center text-gray-400">
11 No image
12 </div>
13 )}
14 <h2>{product.name}</h2>
15 <p>${product.price}</p>
16 </article>
17 );
18}
components/ProductGallery.tsx — Full gallery on product page
1"use client";
2
3import Image from "next/image";
4import { useState } from "react";
5
6// images come pre-sorted by position from the API
7export function ProductGallery({ images }: { images: any[] }) {
8 const [selected, setSelected] = useState(0);
9 const current = images[selected];
10 if (!images.length) return null;
11
12 // Pick the best variant for display
13 function getImageUrl(img: any, targetWidth: number) {
14 const WIDTHS = [100, 300, 400, 600, 800, 1000, 1200];
15 const w = WIDTHS.find((v) => v >= targetWidth) ?? 1200;
16 return img.variants?.find((v: any) => v.width === w)?.url;
17 }
18
19 return (
20 <div>
21 {/* Main image */}
22 <Image
23 src={getImageUrl(current, 800)}
24 alt={current.originalFilename}
25 width={800}
26 height={600}
27 unoptimized
28 />
29
30 {/* Thumbnails */}
31 <div className="flex gap-2 mt-4">
32 {images.map((img, i) => (
33 <button key={img.id} onClick={() => setSelected(i)} className={i === selected ? "ring-2" : ""}>
34 <Image src={getImageUrl(img, 100)} alt="" width={80} height={80} unoptimized />
35 </button>
36 ))}
37 </div>
38 </div>
39 );
40}

Note: Always display raster images via variants — never the signed original URL. Variants are CDN-cached and permanent. Small listing widths are pre-generated on upload; larger widths are generated on first request. If a variant isn't ready in the brief window right after upload, show a placeholder — it's cached once built. SVGs are served directly as originals (no variants needed).

Building with an AI assistant?

Point it at the complete reference, or connect the MCP server so it can read these docs and use your project.