Ryan KatayiSenior full-stack engineer
    All sessions

    Engineering notes — ExplainersUsing Vercel Blob TTL for automatic file deletion

    How to use Vercel Blob TTL automatic deletion to replace cron-based cleanup for uploads, exports and logs in a Next.js app while keeping data retention explicit.

    9 min

    #Vercel#Next.js#TypeScript#Infrastructure

    Vercel Blob now lets you delete files automatically after a fixed number of days. Instead of a background script or cron job, you write blobs with a TTL and Vercel deletes them once they expire. For a Next.js app, this turns “remember to clean up uploads later” into a parameter on the write.

    This post shows how I’d replace ad-hoc cleanup scripts with Blob TTLs for user uploads, exports and logs, and what to watch out for when you have GDPR-style retention rules.

    Why I stopped writing cron jobs for uploads

    Most apps I work on have at least three classes of “should not live forever” files:

    • Temporary uploads before a user finishes a flow
    • One-off exports (CSV, PDF, ZIP) the user downloads once
    • Short-lived logs or artifacts meant for debugging, not for history

    The usual pattern is:

    1. Write the file.
    2. Store the URL and maybe an expires_at column in Postgres.
    3. Run a cron or scheduled job that periodically deletes old files and maybe cleans the DB rows.

    That works, but it spreads responsibility across multiple systems. Your app server writes the file. Your database stores its lifetime policy. Your cron script enforces it. If the job fails for a week, your “24-hour” exports may sit around for months.

    Vercel’s announcement describes the new behavior like this:

    "Vercel Blob can now delete blobs automatically. Pass ttlDays when you write a blob and it is deleted that many days after upload, from 1 to 730 days."

    — Vercel changelog

    So the retention rule can move to the storage layer. If you say “exports live for 7 days”, you make that a property of the blob write itself.

    I still keep metadata in the database for some flows, especially where a user can request deletion earlier. But the safety net is now in Blob, not in a job I might forget to redeploy.

    How Vercel Blob TTL automatic deletion works

    From Vercel’s Blob TTL announcement:

    • You pass ttlDays when you write a blob.
    • TTL can be from 1 to 730 days.
    • The TTL counts from the blob’s upload date.
    • You can use TTLs for “session transcripts, exports, and temporary uploads”.
    • ttlDays works on put(), copy(), putImage(), multipart uploads and presigned upload URLs.
    • Every write result and head() response now includes expiresAt.
    • setTtl() can change or remove TTL for existing blobs, one URL or up to 1,000 at a time.

    Once a blob passes its TTL, Vercel deletes it for you. You no longer need a separate delete call or cleanup job for that lifecycle.

    Here’s an illustrative example of how that might look in a Next.js Route Handler that stores a 7‑day export:

    // app/api/exports/route.ts
    import { NextRequest, NextResponse } from "next/server";
    import { put, head, setTtl } from "@vercel/blob";
    
    export async function POST(req: NextRequest) {
      const { userId, payload } = await req.json();
    
      // 1. Generate export content (CSV, JSON, etc.). This is app-specific.
      const fileContents = JSON.stringify(payload);
    
      // 2. Store in Blob with a TTL of 7 days.
      const result = await put(`exports/${userId}/${Date.now()}.json`, fileContents, {
        access: "public", // or "private", depending on your needs
        ttlDays: 7,
      });
    
      // result.expiresAt tells you when Vercel will delete this blob
      return NextResponse.json({
        url: result.url,
        expiresAt: result.expiresAt,
      });
    }
    
    // Example of checking TTL later via head()
    export async function GET(req: NextRequest) {
      const url = new URL(req.url);
      const blobUrl = url.searchParams.get("blobUrl");
    
      if (!blobUrl) return new NextResponse("Missing blobUrl", { status: 400 });
    
      const info = await head(blobUrl);
    
      return NextResponse.json({
        size: info.size,
        uploadedAt: info.uploadedAt,
        expiresAt: info.expiresAt,
      });
    }
    
    // Example of extending or clearing TTL for a list of blobs
    export async function PUT(req: NextRequest) {
      const { blobUrls, ttlDays } = await req.json();
    
      // ttlDays: number | null, where null clears the TTL
      await setTtl(blobUrls, ttlDays);
    
      return new NextResponse(null, { status: 204 });
    }

    That’s not from Vercel’s docs. It’s a pattern that uses the capabilities described: ttlDays on write, and expiresAt coming back from writes and head().

    Vercel describes the cost like this:

    "Setting a TTL costs one Advanced Operation per started 60 days, on top of the write. A 7-day TTL costs one, and the 730-day maximum costs 13."

    — Vercel changelog

    Clearing a TTL and the deletions themselves are free. You can track TTL operations in the Blob section of the Observability tab.

    So if you set short TTLs for temporary files, you pay one extra Advanced Operation per blob. Long-lived logs and archives that use near the 730-day maximum will cost more.

    Migrating cron-based cleanup to Blob TTLs

    If you currently have a Next.js app plus a separate cron cleanup script, I’d migrate in three steps.

    1. Start writing new blobs with TTLs

    Identify each category of blob and give it a concrete retention rule:

    • Temporary uploads: 1–7 days
    • Exports: 7–30 days
    • Short-lived logs: 1–14 days

    Then add ttlDays to your write calls for new blobs. For example, for temporary uploads initiated from the browser via a presigned URL, you can set the TTL when you create that URL. ttlDays works with presigned upload URLs, so you don’t need to trust the client to send this.

    In a typical Next.js server route that creates a presigned URL, you’d set a TTL there and return it to the client. The exact code depends on your existing Blob integration, but the key is: the TTL lives in the server-side call that issues the upload link.

    2. Keep the old cron until you age out legacy blobs

    Existing blobs without TTLs won’t be deleted automatically. The safe approach is:

    • Continue running your old cleanup job for blobs created before the switch.
    • Optionally, have that job also call setTtl() on older blobs you want to expire, instead of deleting them directly.

    setTtl() works on “one URL or up to 1,000 at a time, without re-uploading them.” That’s helpful for a one-time migration where you read candidate blobs from your database and batch-assign TTLs.

    If your legacy job is deleting both Blob objects and database rows, you can gradually change it to only clean the database rows once you’re confident Blob TTLs are doing their work.

    3. Move to DB-only cleanup and Blob TTLs

    After your oldest pre-TTL blobs have either expired naturally or been handled by the migration job, you can simplify:

    • Let Blob TTLs handle storage deletion.
    • Use a lightweight daily job to remove database rows whose expires_at is in the past, or mark them as expired.

    For apps where everything is already in Next.js, this can be as simple as a Vercel Daemon or scheduled function that runs database-only cleanup. Blob itself no longer needs to be touched from the job.

    Patterns for GDPR-style retention windows

    The announcement explicitly calls out “session transcripts, exports, and temporary uploads” as TTL candidates. That’s the same set of data many teams worry about under retention policies and user deletion requirements.

    Within the constraint that the TTL counts from upload time and must be 1–730 days, some workable patterns are:

    Fixed retention per category

    Map each data category to a single TTL value, configured in code or environment variables:

    • SESSION_TTL_DAYS = 30
    • UPLOAD_TTL_DAYS = 7
    • EXPORT_TTL_DAYS = 14

    Then use the corresponding ttlDays whenever you write that blob type. This makes review straightforward, because your code encodes the retention.

    User-triggered early deletion

    If a user requests deletion of their data, you have two levers:

    • Immediate delete: call your delete logic and then remove any database references.
    • Early expiry: call setTtl() with ttlDays: 1 on all relevant blobs and run a process that hides those records from the UI right away.

    You can also remove TTL entirely with setTtl() by changing or removing the TTL. For GDPR-style policies, I would avoid removing TTLs; I’d only shorten or delete.

    Retention changes over time

    Regulations or internal policies might change your required retention. You don’t need to re-upload every blob:

    • For future blobs, update the ttlDays constant in code.
    • For existing blobs, batch setTtl() per category from a migration script.

    Because setTtl() works without re-uploading, the migration is mostly about carefully selecting which URLs to include in each batch and ensuring you respect the 1–730 day window.

    This does not cover complex legal requirements around audit trails or backups, but it gives you a concrete knob directly on the blob storage layer instead of only in application logic.

    Pitfalls: idempotency, soft delete, debugging expired blobs

    TTL-based deletion does change how you structure some of your code paths.

    Idempotent cleanup and retries

    Previously, your cleanup job might have been the only place that called delete() on a blob. With TTLs, there are at least three actors:

    • Your application code deleting blobs directly
    • Your migration or admin scripts calling setTtl()
    • Vercel’s TTL process deleting blobs after expiry

    This makes idempotency more important. Application delete paths should tolerate “blob already gone” cases without treating them as failures, because the TTL may have fired first.

    Soft-delete vs hard-delete

    A TTL is always a hard delete of the blob itself. If your business logic needs a soft-delete period, keep that entirely in your database:

    • Add a deleted_at or hidden_at column.
    • Hide entries from the UI as soon as the user deletes them.
    • Still attach a TTL to the underlying blob at upload time so the physical storage doesn’t last longer than needed.

    Your cron or daemon can then clean up soft-deleted rows after some grace period without worrying about storage.

    Debugging expired blobs with expiresAt

    When something disappears “too early” from a user’s perspective, you need to know if Blob TTLs did it.

    Vercel says “Every write result and head() response now includes expiresAt, so you know when a blob is due for deletion.” I’d lean on that in two places:

    • Store expiresAt alongside the blob URL in your database, so you can show it in admin tools and logs.
    • Use head() in debug tooling to confirm what TTL is currently set without downloading the blob.

    If someone reports a missing export, you can check whether the TTL was too aggressive, or if another path deleted it early.

    Trying it with the CLI and SDK

    Vercel calls out both the CLI and the SDK in this release.

    From the SDK side, they mention installing:

    npm install @vercel/blob@2.9.0

    For CLI workflows, if you’re already using vercel blob for uploads, you can start experimenting with TTLs directly from your terminal:

    • In Vercel CLI 65.16.0 and later, you can pass --ttl-days to vercel blob put, put-image, copy or presign.
    • You can use vercel blob set-ttl on existing blobs.

    A minimal exploration path is:

    1. Upload a test blob with vercel blob put --ttl-days 7.
    2. Inspect it in the dashboard’s Blob section and check expiresAt.
    3. Change its TTL with vercel blob set-ttl.

    You can then replicate the same pattern from your Next.js code using the SDK methods rather than the CLI.

    When I wouldn’t rely only on TTLs

    I wouldn’t treat Blob TTLs as the whole story in a few cases:

    • Legal or contractual retention that’s more complex than “X days from upload”. TTLs are upload-based and have a 1–730 day range; you may still need application logic and database state beyond that.
    • Cross-provider storage. If your app writes to other stores (S3, Supabase Storage, third-party APIs) as well as Vercel Blob, you still need coordinated cleanup, not just TTLs on one of them.
    • Very long-lived archives. If you intend to store files for longer than 730 days, you can’t express that directly as a Blob TTL under the current limits.

    TTL is a strong default guardrail, not a universal solution. I’d still design explicit deletion flows in the app and treat TTLs as the last line of defense when something slips through.

    If you’re running a Next.js product on Vercel and want to untangle blob lifecycles, background jobs and data retention policy, I help teams do that kind of work end to end as a Next.js developer.

    Sources

    Now playingCudioGet in touch