DEV Community

Cover image for Vercel 413 on file uploads: skip your API route
Varsha
Varsha

Posted on Originally published at medialit.cloud

Vercel 413 on file uploads: skip your API route

You deploy a Next.js app to Vercel, add a file upload, and it works with a small test image. Then someone uploads a real photo and the request fails with 413 FUNCTION_PAYLOAD_TOO_LARGE.

Why Vercel returns 413

Vercel's function limits page says functions accept request bodies up to 4.5 MB by default. A 20 MiB limit is available in public beta for the Node.js, Python and Bun runtimes, but only if you enable fluid compute, set function memory to Performance (4 GB, Pro and Enterprise plans) and set VERCEL_SUPPORT_LARGE_REQUEST_BODY=1. Edge-runtime functions keep the 4.5 MB limit. Anything over the limit gets the 413 error.

The usual upload code looks like this:

// app/api/upload/route.ts  (the pattern that hits 413)
export async function POST(request: Request) {
  const form = await request.formData(); // the whole file arrives here
  const file = form.get("file") as File;
  // ...then forward it to storage
}
Enter fullscreen mode Exit fullscreen mode

Vercel never reaches this code for a big file. It rejects the request first.

The root issue is the route, not the limit

Raising the limit helps if you truly need the bytes in a function. For uploads you usually don't. Your route is only a middleman: it receives the file, then forwards it somewhere else. That costs you memory, request time and a hard size ceiling, and gives you nothing.

The general fix has two parts:

  1. The browser uploads the file directly to the service that stores it.
  2. Your server only does the parts that need your secrets and your rules: decide who may upload, hand out a short-lived permission, and record the result.

Your route then handles a few hundred bytes of JSON, whatever the file size.

The flow with MediaLit

MediaLit is an open-source media upload and processing API. Its browser upload flow has three steps, described in the concepts docs:

  1. The browser asks your server for an upload signature.
  2. Your server checks the user, then asks MediaLit for a signature using the API key.
  3. The browser uploads the file to MediaLit with that signature. Your API key never reaches the browser.

One detail to be exact about: the bytes go from the browser to MediaLit's API, not to your bucket by a presigned URL. On a self-hosted server, MediaLit then streams the upload into your S3-compatible bucket as an S3 multipart upload. Either way, the file never touches your Vercel function.

Uploads then start out temporary. A temporary file works right away, but it is not listed and is deleted after 24 hours. When your app actually keeps the file, for example when the user saves the form, your server seals it.

1. The signature route

Install the SDK and set your environment variables:

npm install medialit @medialit/uploader
Enter fullscreen mode Exit fullscreen mode
# .env.local
MEDIALIT_API_KEY=YOUR_API_KEY
# Only for self-hosting. Defaults to https://api.medialit.cloud
# MEDIALIT_ENDPOINT=https://your-medialit-server.example.com
Enter fullscreen mode Exit fullscreen mode

The medialit package reads MEDIALIT_API_KEY and MEDIALIT_ENDPOINT itself. It runs on the server only and refuses to start in a browser. Its createSignatureHandler helper builds the route for you:

// app/api/medialit/signature/route.ts
import { createSignatureHandler } from "medialit";
import { getSession } from "@/lib/auth"; // your app's auth

export const POST = createSignatureHandler({
  // Anyone who passes this check can upload to your MediaLit app.
  authorize: async (request) => {
    const session = await getSession(request);
    return session ? { group: session.userId } : false;
  },
});
Enter fullscreen mode Exit fullscreen mode

It answers with { signature, endpoint }, or a 401 if authorize returns false. Under the hood it calls medialit.getSignature(), and returning { group } puts every file uploaded with that signature into that group. You can read the source if you want to see exactly what it does.

2. The browser upload

On the client, @medialit/uploader fetches a signature from your route, then uploads with the tus resumable protocol:

// app/avatar-upload.tsx
"use client";

import { useState } from "react";
import { uploadFile } from "@medialit/uploader";

export function AvatarUpload() {
  const [status, setStatus] = useState("");

  async function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      // Goes straight to MediaLit, not through your Vercel function.
      const media = await uploadFile(file, {
        signatureEndpoint: "/api/medialit/signature",
        access: "public",
        onProgress: ({ percentage }) =>
          setStatus(`Uploading ${Math.round(percentage)}%`),
      });

      // Only the ID goes to your server.
      await fetch("/api/avatar", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ mediaId: media.mediaId }),
      });
      setStatus("Saved");
    } catch (err) {
      setStatus(err instanceof Error ? err.message : "Upload failed");
    }
  }

  return (
    <>
      <input type="file" accept="image/*" onChange={onChange} />
      <p>{status}</p>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Files go up in chunks, 48 MiB per request by default, and an interrupted upload of the same file resumes where it stopped. If you use React, @medialit/react wraps this in a drop-zone component with progress and retry.

3. Seal it when you keep it

The save route receives a media ID, which is tiny, and seals the file:

// app/api/avatar/route.ts
import { MediaLit } from "medialit";
import { getSession } from "@/lib/auth";

export async function POST(request: Request) {
  const session = await getSession(request);
  if (!session) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { mediaId } = await request.json();
  if (typeof mediaId !== "string") {
    return Response.json({ error: "Bad request" }, { status: 400 });
  }

  // Created inside the handler so the key is read at request time.
  const medialit = new MediaLit();

  // Only seal files this user uploaded.
  const existing = await medialit.get(mediaId);
  if (existing.group !== session.userId) {
    return Response.json({ error: "Not found" }, { status: 404 });
  }
  const media = await medialit.seal(mediaId);

  // Save media.mediaId and media.file with your user record.
  return Response.json({ mediaId: media.mediaId, url: media.file });
}
Enter fullscreen mode Exit fullscreen mode

If the user closes the tab without saving, you never call seal, and MediaLit deletes the temporary file after 24 hours. Sealing a file that is already sealed returns it unchanged. One thing to know: sealing a public file moves it to permanent public storage and its URL changes. Store the URL the seal call returns, or store the mediaId and look the URL up later.

Hosted or self-hosted

The code above is the same for both. On medialit.cloud you only need an API key. If you self-host, MediaLit stores files in your own S3-compatible bucket, and you set MEDIALIT_ENDPOINT to your server. If your server reaches MediaLit at a different address than browsers do, as it might inside Docker, createSignatureHandler takes a publicEndpoint option for the address the browser should use.

Tradeoffs

  • You still need a server route. Something has to decide who may upload. authorize is that decision. A signature expires after 24 hours or once a file has been uploaded with it, and uploads count against your storage, so only hand signatures to users you trust.
  • The file isn't validated by your code before it lands. Your server sees the media ID after the upload. Check type and size in the browser for a better experience, and check what you stored when you seal.
  • Check ownership before you seal. Always check that a media ID belongs to the current user before you seal or store it.
  • It's one more service. You trade a size limit for an extra network hop in your architecture.

Wrapping up

A 413 on Vercel means the file shouldn't be going through your function. Keep your route small, sign the upload, let the browser send the bytes elsewhere, and keep only what your app uses.

Gregale wrote about this problem recently too, and it's worth a read.

MediaLit is on GitHub and hosted at medialit.cloud.

Top comments (0)