---
title: Build a temporary file sharing app with Neon Object Storage
description: Every upload gets its own Neon project and bucket. Links expire in an hour, people can claim the project to keep files, and 1K users cost about $52 a month.
url: https://rishi.app/blog/build-a-temporary-file-sharing-app-with-neon-object-storage
author: Rishi Raj Jain
published_at: 2026-11-15T05:40:02.225Z
updated_at: 2026-11-16T08:55:20.622Z
---

# Build a temporary file sharing app with Neon Object Storage

This guide builds a temporary file sharing app on [Neon Object Storage](https://neon.com/docs/storage/overview), where every visitor's upload gets its own Neon project and bucket, to ensure no two visitors share files or credentials. Files are uploaded straight from the browser, share links automatically expire after an hour, and visitors can claim the project to keep their files.

You'll use Next.js, the [Neon API](https://neon.com/docs/reference/api), [Lakebase Postgres](https://neon.com/docs/postgres/overview) to track uploads, and [Vercel Cron](https://vercel.com/docs/cron-jobs) to delete expired projects.

## Demo

Try it at [share-files-with-basket.vercel.app](https://share-files-with-basket.vercel.app).

The tabs below cover each stage of a shot:

**Before the shot**

The ball carries the file type on it. Drag a file from your desktop onto the hoop, pick one with **Choose file**, or focus the ball and press Enter to shoot the sample image.

![Basket app ready for an upload, with a basketball labelled moodboard.png below the hoop](https://rishi.app/assets/blog/build-a-temporary-file-sharing-app-with-neon-object-storage/basket-home.webp)

**Spinning up Neon**

The file drops through the rim and the server starts creating a Neon project in AWS US East (Ohio).

![Basket app spinning up a Neon project in us-east-2 as the ball drops through the hoop](https://rishi.app/assets/blog/build-a-temporary-file-sharing-app-with-neon-object-storage/basket-provisioning.webp)

**Adding a bucket**

The project is ready, so the server adds a public bucket called `uploads` and asks Neon for a presigned upload URL. In this run, the project took 0.4 seconds and the bucket 0.2 seconds.

![Basket app with the Neon project and the public uploads bucket created, uploading moodboard.png](https://rishi.app/assets/blog/build-a-temporary-file-sharing-app-with-neon-object-storage/basket-bucket.webp)

**Swish**

The browser has uploaded the file straight to the bucket. You get a public link, a countdown to the one-hour buzzer, and a link to claim the project.

![Basket app after the upload, with the public link to moodboard.png, the countdown to the buzzer and a button to claim the project](https://rishi.app/assets/blog/build-a-temporary-file-sharing-app-with-neon-object-storage/basket-done.webp)


## Why Neon Object Storage instead of Supabase Storage

The platform I'm building on this pattern gives every signed-in user their own project and bucket. Storage costs about the same on both, so the bill depends on what an idle project costs:

- **Idle projects cost almost nothing on Neon.** Compute [scales to zero](https://neon.com/docs/introduction/scale-to-zero), so an unused project only pays for about 30 MB of storage, roughly a cent a month. On Supabase, every project runs its own Postgres instance, billed by the hour and never paused on paid plans, at about $9.81 a month.
- **Egress is included per project.** Neon includes [500 GB of network transfer](https://neon.com/docs/introduction/network-transfer) per project, shared by Postgres and Object Storage. Supabase's egress quotas cover the whole organization.
- **There's no base fee.** Neon's [paid plans](https://neon.com/pricing) have no monthly minimum, while Supabase Pro starts at $25.

For 1K users, that's about $52 a month on Neon against about $9.86K on Supabase. Supabase is slightly cheaper per stored GB ($0.0213 against $0.023), and it can put every user in one project with Row Level Security, but then all users share one project, one set of keys and one egress quota.

**Cost breakdown for 1K users**

Prices are from the Neon and Supabase pricing pages as of November 2026. The estimate assumes:

- 1K signed-in users, each with their own project and bucket
- One shared project for the app database and auth, on both platforms
- Each user shares 30 files a month at 8 MB on average, so 240 GB uploaded across all users
- Every file downloaded 5 times within its hour, so 1.2K GB of downloads a month
- Files deleted after an hour, so about 0.33 GB stored on average (240 GB × 1 hour / 730 hours)

| | Neon (Scale) | Supabase (Pro) |
|---|---|---|
| Base plan | $0, no monthly minimum | $25, includes $10 of compute credits |
| Auth for 1K users | $0 (Managed Better Auth, up to 1M MAU per project) | $0 (100K MAU included) |
| Shared app database compute | $40.52 (0.25 CU always on, 182.5 CU-hours at $0.222) | $0 (Micro instance covered by the credits) |
| Per-user project compute | $0.93 (each scales to zero a minute after it's created) | $9.81K (1K Micro instances at $0.01344/hour, always on) |
| Postgres storage | $10.68 (30.5 GB at $0.35/GB-month: about 30 MB per user project plus the app database) | $0 (8 GB disk included per project) |
| Backups and restore | Under $0.10 (instant restore at $0.20/GB-month on a few MB of changes) | $0 (daily backups included) |
| Object storage | $0.01 (0.33 GB at $0.023/GB-month, no per-request charge) | $0 (100 GB included) |
| Downloads (egress) | $0 (500 GB included per project) | $21.30 to $85.50 |
| **Total** | **about $52** | **about $9.86K to $9.92K** |

Supabase's egress quotas are 250 GB uncached and 250 GB cached for all 1K projects together. If the CDN caches every download after the first, 240 GB is uncached (inside the quota) and 960 GB is cached, so 710 GB × $0.03 = $21.30. If nothing is cached, 950 GB × $0.09 = $85.50.

A few things to keep in mind:

- Neon's Free and Launch plans include 100 projects, so 1K users needs Scale, which includes 1K and raises the limit on request.
- Scale is also the only plan where the one-minute scale-to-zero in `createProject` applies. On Free and Launch, compute suspends after five minutes idle.
- The per-user compute line assumes all 1K users signed up this month. Projects from earlier months stay suspended and cost only their storage.
- Supabase with every user in one shared project comes to about $46 to $110 a month.


## Prerequisites

- Node.js 24 or newer
- A [Neon](https://console.neon.tech) account, with admin access to the organization the upload projects go in
- A [Vercel](https://vercel.com) account

## Create the Next.js application

The animation alone is a few hundred lines, so clone the project and walk through the parts that talk to Neon:

```bash
git clone https://github.com/rishi-raj-jain/share-files-with-basket
cd share-files-with-basket
npm install
```

The key dependencies are:

- `@neondatabase/serverless` to query Postgres over HTTP from the API routes
- `@dotenvx/dotenvx` to load `.env.local` for the dev server and the migration script

Object Storage is reached through the Neon API with plain `fetch`, so there's no S3 SDK, and the server holds a Neon API key instead of storage credentials.

The project has the following structure:

```plaintext
share-files-with-basket
├── scripts
│   └── migrate.mjs                creates the tables
└── src
    ├── app/api
    │   ├── cron/cleanup/route.ts  deletes expired projects
    │   ├── drops/route.ts         provisions and presigns
    │   └── session/route.ts       restores a session on reload
    ├── components
    │   └── hoop-uploader.tsx      uploads with progress
    └── lib
        ├── client-ip.ts           hashed IP for daily limits
        ├── db.ts                  control database client
        ├── limits.ts              caps, region, content types
        ├── neon-api.ts            Neon API wrapper
        └── session.ts             session cookie lookups
```

## Configure Neon with the Neon CLI

There are two kinds of Neon projects in this app:

- One **control project** that you create once. Its Postgres database records which project belongs to which browser and every shared file.
- Many **upload projects** that the app creates through the Neon API, one per visitor. Each has a bucket.

[Install the Neon CLI](https://neon.com/docs/cli/install) and log in, which opens a browser to sign in or sign up:

```bash
npm i -g neon@latest
neon login
```

From the project directory, create the control project and [link](https://neon.com/docs/cli/link) the directory to it:

```bash
neon link --no-config
```

Pick the organization the upload projects should go in, choose **+ Create new project**, and pick **AWS US East (Ohio)** (`aws-us-east-2`), the [region](https://neon.com/docs/introduction/regions) the upload projects use. The CLI writes a `.neon` file and pulls `DATABASE_URL` and `DATABASE_URL_UNPOOLED` into `.env.local`. `--no-config` skips creating a `neon.ts`, since the control project only needs Postgres.

### Create an organization API key

The app manages upload projects through the Neon API, so it needs an [API key](https://neon.com/docs/manage/api-keys) owned by your organization. Your organization ID is the `orgId` in `.neon` (or run `neon orgs list`). Create the key with [`neon api-keys`](https://neon.com/docs/cli/api-keys) and append it to `.env.local`:

```bash
echo "NEON_API_KEY=$(neon api-keys create --name share-files --org-id org-... -o json | jq -r .key)" >> .env.local
```

The key is shown only once, so the command writes it straight to the file. It reaches every project in the organization, including ones created later, so give the upload projects an organization of their own. Creating it needs organization admin permissions.

Finally, add the organization ID and two random secrets. `.env.local` then looks like this:

```env filename=".env.local"
DATABASE_URL=postgresql://...-pooler.us-east-2.aws.neon.tech/neondb?sslmode=require
DATABASE_URL_UNPOOLED=postgresql://....us-east-2.aws.neon.tech/neondb?sslmode=require
NEON_API_KEY=napi_...
NEON_ORG_ID=org-...
CRON_SECRET=a-long-random-string
IP_SALT=another-long-random-string
```

Generate `CRON_SECRET` and `IP_SALT` with `openssl rand -hex 32`. `CRON_SECRET` protects the cleanup route, and `IP_SALT` salts the visitor IP hashes the app stores.

## Create the database schema

`scripts/migrate.mjs` creates two tables in the control database. `drops` tracks each upload project, and `uploads` tracks each file shared from it:

```mermaid title="The control database: one drops row per upload project, one uploads row per shared file"
erDiagram
  drops ||--o{ uploads : "shares"
  drops {
    uuid id PK
    text project_id UK "upload project"
    text branch_id "its default branch"
    text s3_endpoint "bucket host"
    text claim_url "claim link"
    timestamptz expires_at "end of the hour"
    text owner_hash "hashed session"
    text ip_hash "hashed visitor IP"
    timestamptz deleted_at "deleted or claimed"
  }
  uploads {
    bigint id PK
    text project_id "drops.project_id"
    text file_name
    text file_type
    bigint file_size
    text public_url "share link"
  }
```

The migration is safe to run repeatedly, and it connects with `DATABASE_URL_UNPOOLED` because schema changes belong on a direct connection, not the pooler. Run it with:

```bash
npm run db:migrate
```

## Build a Neon API client

Shared constants are in `src/lib/limits.ts`:

```ts filename="src/lib/limits.ts"
export const MAX_BYTES = 10 * 1024 * 1024
export const CLAIM_WINDOW_SECONDS = 60 * 60
export const MAX_FILES_PER_PROJECT = 20
export const PROJECT_PREFIX = 'hoop-drop-'
export const BUCKET = 'uploads'
export const REGION = 'aws-us-east-2'
```

In the code above:

- `MAX_BYTES` caps each file at 10 MB, and `MAX_FILES_PER_PROJECT` caps each project at 20 files.
- `CLAIM_WINDOW_SECONDS` is the one-hour window for both the share link and the claim link.
- `PROJECT_PREFIX` names every upload project, so the cleanup cron can find the projects it owns.

Every Neon API call in the app goes through one helper in `src/lib/neon-api.ts`:

```ts filename="src/lib/neon-api.ts" collapse={3-10,16-23}
const API = 'https://console.neon.tech/api/v2'

export class NeonApiError extends Error {
  constructor(
    public status: number,
    message: string,
  ) {
    super(message)
  }
}

async function call<T>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
  // 423 means another operation still holds the project lock, so wait and retry.
  for (let attempt = 0; attempt < 40; attempt++) {
    const res = await fetch(API + path, {
      method: init.method ?? 'GET',
      headers: {
        authorization: `Bearer ${process.env.NEON_API_KEY}`,
        accept: 'application/json',
        ...(init.body ? { 'content-type': 'application/json' } : {}),
      },
      body: init.body ? JSON.stringify(init.body) : undefined,
      cache: 'no-store',
    })
    if (res.status === 423) {
      await new Promise((r) => setTimeout(r, 250))
      continue
    }
    const text = await res.text()
    if (!res.ok) {
      let message = `Neon API ${res.status}`
      try {
        message = JSON.parse(text).message ?? message
      } catch {}
      throw new NeonApiError(res.status, message)
    }
    return (text ? JSON.parse(text) : null) as T
  }
  throw new NeonApiError(423, 'Neon project stayed locked for too long')
}
```

In the code above:

- A new project briefly answers `423 Locked` while its creation operations finish. Retrying every 250 ms, up to 40 times, turns that into a short delay instead of a failed upload.
- Any other error is thrown as a `NeonApiError` that keeps the HTTP status, so callers can tell "this project is gone" (a 4xx) apart from "Neon had a problem" (a 5xx).

## Provision a Neon project per visitor

A new upload project is one [`POST /projects`](https://neon.com/docs/reference/api/projects/create-project) call:

```ts filename="src/lib/neon-api.ts"
export async function createProject(suffix: string) {
  const data = await call<{ project: { id: string }; branch: { id: string } }>('/projects', {
    method: 'POST',
    body: {
      project: {
        name: `${PROJECT_PREFIX}${suffix}`,
        region_id: REGION,
        org_id: process.env.NEON_ORG_ID,
        default_endpoint_settings: { suspend_timeout_seconds: 60 },
      },
    },
  })
  return { projectId: data.project.id, branchId: data.branch.id }
}
```

In the code above:

- `org_id` creates the project in your organization, so the cron can list and delete it and the visitor can claim it.
- `suspend_timeout_seconds: 60` scales the project's Postgres compute to zero after a minute idle, since the app never queries that database.
- Object Storage is attached to a branch, so the app keeps the default branch's `branchId` for every call that follows.

## Create a public Object Storage bucket

Object Storage comes up shortly after the project does. The app polls the branch's [storage state endpoint](https://neon.com/docs/reference/api/storage/get-project-branch-storage) until it reports an S3 endpoint:

```ts filename="src/lib/neon-api.ts"
export async function waitForStorage(projectId: string, branchId: string) {
  for (let attempt = 0; attempt < 40; attempt++) {
    try {
      const s = await call<{ enabled: boolean; s3_endpoint?: string }>(`/projects/${projectId}/branches/${branchId}/storage`)
      if (s.enabled && s.s3_endpoint) return s.s3_endpoint
    } catch (err) {
      if (!(err instanceof NeonApiError) || err.status !== 404) throw err
    }
    await new Promise((r) => setTimeout(r, 250))
  }
  throw new Error('Object storage did not come up in time')
}
```

The endpoint returns 404 until the branch is registered with Object Storage, so the loop retries every 250 ms for up to 10 seconds. It gives up after that because a 404 can also mean the region has no Object Storage. Any other error stops it right away.

Once storage is up, the app [creates a bucket](https://neon.com/docs/reference/api/buckets/create-project-branch-bucket) with `public_read` access:

```ts filename="src/lib/neon-api.ts"
export function createPublicBucket(projectId: string, branchId: string) {
  return call(`/projects/${projectId}/branches/${branchId}/buckets`, {
    method: 'POST',
    body: { name: BUCKET, access_level: 'public_read' },
  })
}
```

In a [`public_read` bucket](https://neon.com/docs/storage/buckets), anyone can read an object without a credential, while writes still need one. So the share link is just the object's address on the branch's storage endpoint:

```ts filename="src/app/api/drops/route.ts"
const publicUrlFor = (endpoint: string, key: string) => `${endpoint}/${BUCKET}/${key.split('/').map(encodeURIComponent).join('/')}`
```

The key starts with six random bytes, so links can't be guessed by walking file names:

```ts filename="src/app/api/drops/route.ts"
function safeKey(name: string) {
  const clean = name
    .normalize('NFKD')
    .replace(/[^\w.-]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 80)
  return `${randomBytes(6).toString('hex')}/${clean || 'file'}`
}
```

A shared link ends up looking like `https://br-late-butterfly-b4gl8qwa.storage.c-6.us-east-2.aws.neon.tech/uploads/7b98684a6ad2/moodboard.png`.

## Upload files directly with presigned URLs

The file never passes through the Next.js server. The server asks Neon for a [presigned upload URL](https://neon.com/docs/reference/api/buckets/presign-project-branch-bucket-object) and passes it to the browser:

```ts filename="src/lib/neon-api.ts"
export function presignUpload(projectId: string, branchId: string, key: string, contentType: string) {
  return call<{
    url: string
    method: string
    headers: Record<string, string>
    expires_at: string
  }>(`/projects/${projectId}/branches/${branchId}/buckets/${BUCKET}/objects/${encodeURIComponent(key)}/presign`, {
    method: 'POST',
    body: {
      operation: 'upload',
      content_type: contentType,
      expires_in_seconds: 600,
    },
  })
}
```

In the code above:

- `operation: 'upload'` asks for a URL the browser can write one object to.
- `content_type` is bound into the signature, so the browser's PUT must send exactly that `Content-Type`, and the bucket serves the object with it.
- `expires_in_seconds: 600` gives the browser ten minutes to start the upload.
- The response carries the method and any headers the upload must send, so the client doesn't hardcode either.

On the client, `src/components/hoop-uploader.tsx` sends the file with `XMLHttpRequest` instead of `fetch`, because XHR reports upload progress and that's what fills the net:

```ts filename="src/components/hoop-uploader.tsx"
function putWithProgress(upload: Ready['upload'], file: File, onProgress: (p: number) => void) {
  return new Promise<void>((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open(upload.method, upload.url)
    for (const [k, v] of Object.entries(upload.headers)) xhr.setRequestHeader(k, v)
    xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total)
    xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Storage returned ${xhr.status}. Shoot again.`)))
    xhr.onerror = () => reject(new Error('The upload dropped. Shoot again.'))
    xhr.send(file)
  })
}
```

This keeps the function out of the data path. A Vercel function accepts request bodies up to 4.5 MB, but here a 10 MB file costs it only a few API calls.

### Restrict the content types the bucket serves

A public bucket on a Neon domain serves whatever `Content-Type` you presigned the upload with. If a visitor uploads an HTML or SVG file and the bucket serves it as `text/html` or `image/svg+xml`, the browser runs its scripts. So the app keeps an allowlist of types that are safe to render inline, and stores everything else as a download:

```ts filename="src/lib/limits.ts"
export const INLINE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif', 'image/heic', 'image/heif', 'application/pdf', 'text/plain', 'text/markdown', 'text/csv']

export const DOWNLOAD_TYPE = 'application/octet-stream'

export function storedType(type: string) {
  return INLINE_TYPES.includes(type) ? type : DOWNLOAD_TYPE
}
```

The client calls `storedType()` too, but the server runs it again before presigning, so a modified client can't ask for `text/html`.

## Transfer project ownership with a claim link

The claim link turns a throwaway project into one the visitor keeps. The app creates a [transfer request](https://neon.com/docs/reference/api/projects/create-project-transfer-request) that lasts as long as the share window:

```ts filename="src/lib/neon-api.ts"
export function createTransferRequest(projectId: string, ttlSeconds: number) {
  return call<{ id: string; expires_at: string }>(`/projects/${projectId}/transfer_requests`, {
    method: 'POST',
    body: { ttl_seconds: ttlSeconds },
  })
}
```

Then it builds a claim URL in the Neon Console from the project ID, the transfer request ID, and a return URL:

```ts filename="src/app/api/drops/route.ts"
const claimUrl = `https://console.neon.tech/app/claim?p=${projectId}&tr=${transfer.id}&ru=${encodeURIComponent(origin)}`
```

In the code above:

- `p` and `tr` identify the project and the transfer request.
- `ru` is where Neon sends the visitor back after the claim, here the app itself.

When a visitor opens the link, they sign in to Neon (or sign up), pick an organization, and the project moves there with its bucket and every file in it. A transfer request works once, and anyone holding the URL can use it, so the app only ever returns it to the browser that created the project.

The app uses the transfer request's `expires_at` as the project's expiry in `drops`, so the countdown in the UI and the end of the claim window are the same moment.

## Build the upload route

`src/app/api/drops/route.ts` runs every step above in order and streams progress to the browser as [NDJSON](https://github.com/ndjson/ndjson-spec), one event per step. That's what moves the ball through the tabs in the demo:

```ts filename="src/app/api/drops/route.ts" collapse={15-18,39-50}
return ndjson(
  async (send) => {
    let projectId: string | null = null
    try {
      let t = Date.now()
      const created = await createProject(randomBytes(3).toString('hex'))
      projectId = created.projectId
      const { branchId } = created
      await sql`
        insert into drops (project_id, branch_id, ip_hash, owner_hash, file_name, file_type, file_size, expires_at)
        values (${projectId}, ${branchId}, ${ip}, ${ownerHash(token)}, ${name}, ${type}, ${size},
                now() + make_interval(secs => ${CLAIM_WINDOW_SECONDS}))
      `
      send({
        step: 'project',
        projectId,
        region: REGION,
        ms: Date.now() - t,
      })

      t = Date.now()
      const endpoint = await waitForStorage(projectId, branchId)
      await createPublicBucket(projectId, branchId)
      send({ step: 'bucket', ms: Date.now() - t })

      const [presign, transfer] = await Promise.all([presignUpload(projectId, branchId, key, type), createTransferRequest(projectId, CLAIM_WINDOW_SECONDS)])
      const publicUrl = publicUrlFor(endpoint, key)
      const claimUrl = `https://console.neon.tech/app/claim?p=${projectId}&tr=${transfer.id}&ru=${encodeURIComponent(origin)}`
      await sql`
        update drops set s3_endpoint = ${endpoint}, claim_url = ${claimUrl}, public_url = ${publicUrl},
          expires_at = ${transfer.expires_at}
        where project_id = ${projectId}
      `
      await sql`
        insert into uploads (project_id, file_name, file_type, file_size, public_url)
        values (${projectId}, ${name}, ${type}, ${size}, ${publicUrl})
      `
      send({
        step: 'ready',
        reused: false,
        projectId,
        region: REGION,
        upload: {
          url: presign.url,
          method: presign.method,
          headers: presign.headers,
        },
        publicUrl,
        claimUrl,
        expiresAt: transfer.expires_at,
      })
    } catch (err) {
      console.error('drop failed', err)
      send({
        step: 'error',
        message: 'Neon blocked that one. Take another shot.',
      })
      if (projectId) {
        // Drop the row too, so a shot Neon blocked doesn't use up one of today's projects.
        // If the delete above failed, the cron still finds the project by its name prefix.
        await deleteProject(projectId).catch(() => {})
        await sql`delete from drops where project_id = ${projectId}`.catch(() => {})
      }
    }
  },
  sessionCookie(token, CLAIM_WINDOW_SECONDS),
)
```

In the code above:

- The `drops` row is written as soon as the project exists, before storage is ready. If anything after that fails, the route still knows which project to delete.
- The presigned upload and the transfer request don't depend on each other, so they run in parallel.
- The `ready` event carries everything the browser needs: the upload URL and headers, the public link, the claim link and the expiry.
- On failure, the route deletes the half-built project and its row. If the delete fails too, the project still carries the `hoop-drop-` prefix, so the cleanup cron removes it.

`sessionCookie` sets an `httpOnly` cookie that lasts as long as the window, and the database stores only its SHA-256 hash in `owner_hash`. If that cookie already has a project with more than two minutes left, the route skips straight to presigning, so later uploads land in the same bucket, up to 20 files.

### Rate-limit project creation

Each new project is a real Neon project in your organization, so the route checks two limits before creating one:

```ts filename="src/app/api/drops/route.ts"
const PER_IP_PER_DAY = Number(process.env.DROPS_PER_IP_PER_DAY ?? 3)
const MAX_ACTIVE = Number(process.env.MAX_ACTIVE_DROPS ?? 25)

// ...

const ip = ipHash(request)
const [{ mine, open }] = (await sql`
  select
    count(*) filter (where ip_hash = ${ip} and created_at > now() - interval '1 day')::int as mine,
    count(*) filter (where deleted_at is null and created_at > now() - interval '2 hours')::int as open
  from drops
`) as { mine: number; open: number }[]
if (mine >= PER_IP_PER_DAY)
  return Response.json({ error: `That's ${PER_IP_PER_DAY} new projects today, the daily limit. Come back tomorrow.` }, { status: 429 })
if (open >= MAX_ACTIVE) return Response.json({ error: 'Every court is taken. Shoot again in a few minutes.' }, { status: 503 })
```

In the code above:

- `mine` counts the projects this visitor created in the last day. The default is 3.
- `open` counts projects that haven't been deleted yet across all visitors. The default cap is 25, which keeps the organization well under a plan's project limit.

The visitor is a SHA-256 hash of their IP, salted with `IP_SALT`, so the database never stores a raw IP. `src/lib/client-ip.ts` counts an IPv6 /64 as one visitor, so cycling through addresses in one block doesn't get past the daily limit.

## Delete expired projects with Vercel Cron

`vercel.json` pins the functions next to the database and schedules the cleanup every ten minutes:

```json filename="vercel.json"
{
  "regions": ["cle1"],
  "crons": [{ "path": "/api/cron/cleanup", "schedule": "*/10 * * * *" }]
}
```

`cle1` (Cleveland) is the closest Vercel region to AWS us-east-2, so Neon API calls and queries take a short hop.

The cleanup route doesn't trust the `drops` table to know which projects exist. It asks Neon instead, by [listing every project](https://neon.com/docs/reference/api/projects/list-projects) in the organization with the `hoop-drop-` prefix:

```ts filename="src/lib/neon-api.ts"
export function listDropProjects() {
  return call<{ projects: { id: string; name: string; created_at: string }[] }>(`/projects?org_id=${process.env.NEON_ORG_ID}&search=${PROJECT_PREFIX}&limit=400`).then((d) =>
    d.projects.filter((p) => p.name.startsWith(PROJECT_PREFIX)),
  )
}
```

In the code above:

- `org_id` scopes the list to your organization, and `limit=400` fetches up to 400 projects in one request.
- `search` matches partial names, so the `startsWith` filter keeps only names that begin with the prefix. A project named `my-hoop-drop-test` is never touched.

Then the route [deletes](https://neon.com/docs/reference/api/projects/delete-project) every project older than the one-hour window:

```ts filename="src/app/api/cron/cleanup/route.ts" collapse={1-9}
import { sql } from '@/lib/db'
import { CLAIM_WINDOW_SECONDS } from '@/lib/limits'
import { deleteProject, listDropProjects, NeonApiError } from '@/lib/neon-api'

export const maxDuration = 300

// Runs every 10 minutes (vercel.json) and only deletes projects older than the
// one-hour window, so nothing goes before its buzzer. A claimed project has
// already moved to the claimer's org, so it no longer shows up in the listing.
export async function GET(request: Request) {
  if (request.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`)
    return new Response('Unauthorized', { status: 401 })
  const cutoff = Date.now() - CLAIM_WINDOW_SECONDS * 1000
  const projects = await listDropProjects()
  const expired = projects.filter((p) => new Date(p.created_at).getTime() < cutoff)
  const deleted: string[] = []
  for (const p of expired) {
    try {
      await deleteProject(p.id)
      deleted.push(p.id)
    } catch (err) {
      if (err instanceof NeonApiError && err.status === 404) deleted.push(p.id)
      else console.error('cleanup failed', p.id, err)
    }
  }
  // Close out every past-expiry row: deleted here, claimed, or already gone.
  const stillOurs = projects.filter((p) => !deleted.includes(p.id)).map((p) => p.id)
  await sql`
    update drops set deleted_at = now()
    where deleted_at is null and expires_at < now() and not (project_id = any(${stillOurs}))
  `
  return Response.json({ checked: projects.length, deleted })
}
```

In the code above:

- Vercel [sends `Authorization: Bearer <CRON_SECRET>`](https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs) with every cron request when the `CRON_SECRET` environment variable is set, so the route rejects anyone else who calls it.
- A 404 from Neon counts as deleted, since the project is already gone. Any other error is logged, and the next run tries again.
- `stillOurs` is every listed project that wasn't just deleted. A past-expiry row whose project isn't in that list is marked deleted, whether this run deleted it or the visitor claimed it.

Listing from Neon handles three cases without extra code:

- A project that was **claimed** has moved to the visitor's organization, so it never shows up in the listing and is never deleted.
- A project whose creation **failed halfway** still carries the prefix, so it gets deleted even if its `drops` row was never written.
- Deleting a project deletes its bucket and every object in it. There's no per-object cleanup.

Neon keeps a deleted project [recoverable for 7 days](https://neon.com/docs/manage/projects#recover-a-deleted-project), at no storage cost, before it's gone for good. Anyone with admin access to your organization can bring the project and its files back during that week, so keep that in mind if you promise visitors their files are deleted.

## Deploy to Vercel

[Deploy with Vercel](https://vercel.com/new/clone?repository-url=https://github.com/rishi-raj-jain/share-files-with-basket)

To deploy:

- Fork [the GitHub repository](https://github.com/rishi-raj-jain/share-files-with-basket).
- Create a **New Project** in the Vercel Dashboard and link it to your fork.
- In **Settings**, set the **Environment Variables** from your `.env.local`, including `CRON_SECRET`. Add `DROPS_PER_IP_PER_DAY` and `MAX_ACTIVE_DROPS` to change the default limits.
- Deploy.

The cron in `vercel.json` registers on the first production deployment. Run `npm run db:migrate` against your control database before the first upload if you haven't already.

---

This is the Markdown version of https://rishi.app/blog/build-a-temporary-file-sharing-app-with-neon-object-storage. Every page on this site is listed with a summary at https://rishi.app/sitemap.md.
