Ploy
Ploy

File Storage

Store, upload and serve files in your Next.js app with Ploy.

File Storage

Store user uploads, images and documents from your Next.js app, and let browsers upload and download them directly with signed URLs.

Configuration

ploy.yaml
kind: nextjs
fs:
  UPLOADS:
    name: uploads
    max_object_size: 10MB

Run pnpm ploy types to add UPLOADS: FileStorageBinding to your env types. During next dev, initPloyForDev() connects the binding to local storage in .ploy/, with the same size limits and signed URLs as production.

Direct uploads from the browser

Create an upload URL in a route handler after checking the user, then upload the file straight to storage from the browser. The file never passes through your server.

app/api/uploads/route.ts
import { NextResponse } from "next/server";
import { getPloyContext } from "@meetploy/nextjs";
import { currentUser } from "@meetploy/nextjs/auth";

export async function POST(request: Request) {
	const user = await currentUser();
	if (!user) {
		return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
	}
	const { contentType } = await request.json();
	const key = `attachments/${user.id}/${crypto.randomUUID()}`;

	const { env } = getPloyContext();
	const upload = await env.UPLOADS.createSignedUrl(key, {
		method: "PUT",
		contentType,
		maxSize: 10 * 1024 * 1024,
		expiresIn: 600,
	});
	return NextResponse.json({ key, ...upload });
}
components/upload-button.tsx
"use client";

export async function uploadFile(file: File): Promise<string> {
	const response = await fetch("/api/uploads", {
		method: "POST",
		body: JSON.stringify({ contentType: file.type }),
	});
	const { key, url, headers } = await response.json();
	const upload = await fetch(url, { method: "PUT", headers, body: file });
	if (!upload.ok) {
		throw new Error(`Upload failed: ${upload.status}`);
	}
	return key;
}

Return a signed GET URL wherever you would have used a public URL, for example for an image in a chat message or a document an AI model should read:

app/api/attachments/[...key]/route.ts
import { NextResponse } from "next/server";
import { getPloyContext } from "@meetploy/nextjs";

export async function GET(
	_request: Request,
	{ params }: { params: Promise<{ key: string[] }> },
) {
	const { env } = getPloyContext();
	const key = (await params).key.join("/");
	// Check that the current user may read this key here.
	const { url } = await env.UPLOADS.createSignedUrl(key, {
		expiresIn: 3600,
		contentDisposition: "inline",
	});
	return NextResponse.redirect(url);
}

Serving files through your app

Stream a file from a route handler when you need your own headers or access checks on every request:

app/files/[...key]/route.ts
import { getPloyContext } from "@meetploy/nextjs";

export async function GET(
	_request: Request,
	{ params }: { params: Promise<{ key: string[] }> },
) {
	const { env } = getPloyContext();
	const file = await env.UPLOADS.get((await params).key.join("/"));
	if (!file) {
		return new Response("Not Found", { status: 404 });
	}
	const headers = new Headers({ ETag: file.httpEtag });
	file.writeHttpMetadata(headers);
	return new Response(file.body, { headers });
}

See File Storage for every method, the signed URL options, limits, and how to migrate from Supabase Storage.

Next Steps

  • Database - Store the keys of uploaded files alongside your data
  • Queues - Process uploads in the background

How is this guide?

Last updated on