Create the GET endpoint
Import the APIRoute
type from "astro" and create a GET endpoint that accepts the locals
parameter.
The locals
object provides access to runtime environment variables and bindings, including the CLOUD_FILES
binding that you'll use to interact with object storage.
Get the bucket and validate configuration
Access the CLOUD_FILES
binding from locals.runtime.env
and validate that the bucket is properly configured.
If the bucket isn't available, return a 500 error with a descriptive message to help with debugging.
List files with pagination support
Use the .list()
method to retrieve files from the bucket.
The method returns an R2Object
list with pagination support. Set a limit
of 500 files per request to balance performance and memory usage. The response includes a truncated
flag indicating if more files are available, and a cursor
for pagination.
Key concepts:
- Pagination: Buckets may contain thousands of files, so you use pagination to retrieve them in manageable chunks
- Cursor-based pagination: Each response includes a cursor that points to the next page of results
Return the files as JSON
Return the complete list of files as a JSON response with proper headers. The listed.objects
array contains all the files from the bucket, including metadata like file names, sizes, and creation dates.
Response format: The returned JSON will contain an array of R2Object
items, each with properties like:
key
: The file name/pathsize
: File size in bytesetag
: Entity tag for cachinghttpEtag
: HTTP-compatible entity taguploaded
: Upload timestampchecksums
: File integrity checksumshttpMetadata
: HTTP headers and metadata