AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Persist User-Uploaded Files Across Deployments in Replit Using Replit Object Storage

Sergio García Encina · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

When developers push a full-stack application from the Replit workspace into a live production deployment, an unexpected failure frequently catches them off guard: user-uploaded avatars, attachments, and generated reports vanish. During development in the workspace, writing a file to ./uploads/ feels reliable. The file sits in the file tree, survives quick manual code edits, and appears to work. But the moment you publish via Replit Deployments—whether on Autoscale or a Reserved VM—the underlying infrastructure changes fundamentally.

At 365Finds, we consider writing user-uploaded files to the local container disk one of the most hazardous anti-patterns in Replit full-stack development. Replit deployments run on immutable, ephemeral container instances. Every time your deployment scales to zero, restarts after a crash, or rebuilds during a git push, the runtime filesystem is wiped clean and reconstituted from your repository build artifact. Even worse, under horizontal autoscaling, an upload handled by instance A will never exist on instance B.

To achieve true data persistence across deployments, your application must decouple binary blob storage from the container filesystem. The native, fully managed solution inside the platform is Replit Object Storage (also surfaced as App Storage in the Replit interface). Here is how it functions, how to configure it, and how to implement it correctly in Node.js and Python.


Why Local Filesystem Writes Fail in Production

Understanding the lifecycle of a Replit deployment clarifies why local disk storage is doomed:

  1. Ephemeral Containers: Production deployments run inside isolated container sandboxes. Runtime disk mutations do not persist when the container recycles.
  2. Stateless Autoscaling: Autoscale deployments spin instances up and down according to incoming HTTP traffic. Two simultaneous requests might hit two distinct virtual instances with independent local filesystems.
  3. Build vs. Runtime Separation: When you deploy, Replit freezes the project files present at build time into an immutable artifact. Any file created while the server is serving web requests exists only in the temporary writable layer of that running instance.

Replit Object Storage bypasses this issue entirely. Backed by Google Cloud Storage under the hood, it operates as an independent, durable cloud bucket accessible concurrently by your development Repl workspace and every production deployment replica.

[ User Browser ]
       |
       |  1. Upload Request (Multipart Form)
       v
[ Replit Deployment Instance ] (Ephemeral Container)
       |
       |  2. Stream Bytes / Buffer
       v
[ Replit Object Storage ] (Persistent Cloud Bucket)
       ^
       |  3. Metadata Reference (Key, MIME, Size, User ID)
[ Replit PostgreSQL ] (Relational Database)

Step 1: Provisioning Replit Object Storage

Replit eliminates the biggest headache of enterprise cloud storage: manual Identity and Access Management (IAM), service account credentials, and JSON secret keys. Access credentials and bucket endpoints are automatically injected into your Repl environment and its deployed containers.

  1. Open your project in the Replit workspace.
  2. In the left-hand sidebar, navigate to the Tools menu.
  3. Locate and select App Storage (or Object Storage).
  4. Click Create Bucket (or initialize the default bucket). Replit assigns an isolated cloud bucket directly linked to your Repl identity.
  5. Note the default bucket configuration. By default, SDK calls initialize against this default bucket without requiring custom environment variables.

Step 2: Implementing Storage in Node.js / TypeScript

The official JavaScript/TypeScript SDK is @replit/object-storage.

Install the package in your Repl shell:

npm install @replit/object-storage multer uuid
npm install --save-dev @types/multer @types/uuid

Critical Rule for File Upload Middleware

Never use multer.diskStorage() to write temporary files to ./uploads. If the server container crashes midway or the disk fills up, you accumulate orphan files. Instead, configure Multer with memory storage (multer.memoryStorage()) to handle the file as an in-memory buffer before streaming directly to Replit Object Storage.

Backend Implementation (Express.js)

import express, { Request, Response } from "express";
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
import path from "path";
import { Client } from "@replit/object-storage";

const app = express();
const client = new Client(); // Automatically resolves credentials and default bucket

// Configure multer to hold uploads temporarily in memory
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 10 * 1024 * 1024, // 10 MB upload ceiling
  },
});

// Upload Endpoint
app.post("/api/upload", upload.single("file"), async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "No file uploaded." });
    }

    // Generate collision-resistant unique key
    const fileExtension = path.extname(req.file.originalname);
    const storageKey = `uploads/${uuidv4()}${fileExtension}`;

    // Upload raw buffer directly to Replit Object Storage
    const uploadResult = await client.uploadFromBytes(storageKey, req.file.buffer);

    if (!uploadResult.ok) {
      console.error("Storage upload error:", uploadResult.error);
      return res.status(500).json({ error: "Failed to persist file in object storage." });
    }

    // Return the storage key and metadata (persist storageKey in PostgreSQL)
    return res.status(201).json({
      success: true,
      storageKey,
      originalName: req.file.originalname,
      mimeType: req.file.mimetype,
      size: req.file.size,
    });
  } catch (error) {
    console.error("Upload handler error:", error);
    return res.status(500).json({ error: "Internal server error." });
  }
});

// Download / Retrieval Endpoint
app.get("/api/files/:key(*)", async (req: Request, res: Response) => {
  try {
    const storageKey = req.params.key;

    // Fetch the binary stream or buffer from Replit Object Storage
    const downloadResult = await client.downloadAsBytes(storageKey);

    if (!downloadResult.ok) {
      return res.status(404).json({ error: "File not found." });
    }

    const buffer = Buffer.from(downloadResult.value);
    
    // Set caching and content headers
    res.setHeader("Cache-Control", "private, max-age=86400");
    return res.send(buffer);
  } catch (error) {
    console.error("Download handler error:", error);
    return res.status(500).json({ error: "Could not retrieve file." });
  }
});

// File Deletion Endpoint
app.delete("/api/files/:key(*)", async (req: Request, res: Response) => {
  try {
    const storageKey = req.params.key;
    const deleteResult = await client.delete(storageKey);

    if (!deleteResult.ok) {
      return res.status(404).json({ error: "File not found or already deleted." });
    }

    return res.status(200).json({ success: true, message: "File removed permanently." });
  } catch (error) {
    console.error("Delete handler error:", error);
    return res.status(500).json({ error: "Could not delete file." });
  }
});

export default app;

Step 3: Implementing Storage in Python

If your backend uses Python (FastAPI or Flask), Replit provides the replit-object-storage library.

Install the package via pyproject.toml or pip:

pip install replit-object-storage fastapi python-multipart uvicorn

Python Implementation (FastAPI)

import uuid
import os
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import Response
from replit.object_storage import Client

app = FastAPI()
client = Client()

@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
    # Read file content into memory
    content = await file.read()
    
    # Enforce file size limit (e.g., 10 MB)
    if len(content) > 10 * 1024 * 1024:
        raise HTTPException(status_code=400, detail="File exceeds 10MB limit.")

    file_ext = os.path.splitext(file.filename)[1]
    storage_key = f"uploads/{uuid.uuid4()}{file_ext}"

    try:
        # Write binary content directly to Replit Object Storage
        client.upload_from_bytes(storage_key, content)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Storage upload failed: {str(e)}")

    return {
        "status": "success",
        "storage_key": storage_key,
        "filename": file.filename,
        "content_type": file.content_type,
        "size_bytes": len(content),
    }

@app.get("/api/files/{storage_key:path}")
def get_file(storage_key: str):
    try:
        data = client.download_as_bytes(storage_key)
        return Response(content=data, media_type="application/octet-stream")
    except Exception:
        raise HTTPException(status_code=404, detail="File not found.")

@app.delete("/api/files/{storage_key:path}")
def delete_file(storage_key: str):
    try:
        client.delete(storage_key)
        return {"status": "success", "message": "File deleted."}
    except Exception:
        raise HTTPException(status_code=404, detail="File could not be deleted.")

The Production Blueprint: Blob Storage vs. Relational Metadata

A common beginner trap is treating Object Storage like a database index. Iterating over files using client.list() to filter uploads by user, creation date, or status will crawl to a halt as your bucket grows.

At 365Finds, our architectural standard pairs Replit Object Storage with a relational database (such as Replit's managed PostgreSQL instance):

ResponsibilityStorage EngineTracked Attributes
Binary BlobReplit Object StorageRaw file bytes, storage key path (uploads/<uuid>.<ext>)
Structured MetadataPostgreSQLFile ID (UUID), user_id, original filename, MIME type, size, upload timestamp

When a user requests their uploaded documents, query PostgreSQL to retrieve their records in sub-millisecond time. Only fetch bytes from Replit Object Storage when the user actually downloads or displays a specific asset.


Replit Object Storage Evaluation: Advantages and Boundaries

We evaluate infrastructure choices based on pragmatic trade-offs. Here is how 365Finds views Replit Object Storage:

Where It Excels

Where You Encounter Limits

For full-stack production applications running on Replit, adopting Replit Object Storage is non-negotiable if your users upload images, audio, or PDFs. It eliminates container wipeout risks permanently while keeping deployment pipelines completely frictionless.


References