🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro File Upload: Handle Files with Actions or Endpoints

Handle an Astro file upload with Actions and z.file() validation or a plain endpoint with formData(): size and type limits, body size config, and where to store files.

#Astro#Server Rendering#Astro File Upload#Actions#Forms

To handle a file upload in Astro, post a multipart/form-data form to an Astro Action declared with accept: 'form' and validate the file with z.file(), or read it in an on-demand endpoint with await request.formData() and formData.get('file'). Either way the upload arrives as a standard File object. Raise security.actionBodySizeLimit for files over 1 MB, check size and type on the server, and store the bytes in object storage rather than on the server’s disk.

Key Takeaways

  • Uploads need on-demand rendering and an adapter.
  • Actions with accept: 'form' pass File values straight to your Zod schema; z.file().max().mime() validates them.
  • Action bodies are limited to 1 MB by default; raise security.actionBodySizeLimit for larger files.
  • Save files to object storage such as S3 or R2; serverless file systems are temporary.

The form

---
// src/pages/upload.astro
import { actions } from 'astro:actions';
export const prerender = false;
const result = Astro.getActionResult(actions.uploadAvatar);
---
<form method="POST" action={actions.uploadAvatar} enctype="multipart/form-data">
  <label for="avatar">Profile photo (PNG or JPEG, max 2 MB)</label>
  <input id="avatar" name="avatar" type="file" accept="image/png,image/jpeg" required />
  <button type="submit">Upload</button>
</form>
{result?.error && <p role="alert">{result.error.message}</p>}
{result?.data && <p>Uploaded {result.data.name}.</p>}

enctype="multipart/form-data" is required; without it the browser sends only the file name. The accept attribute filters the file picker but is not security, so validate on the server too.

The action

// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';

export const server = {
  uploadAvatar: defineAction({
    accept: 'form',
    input: z.object({
      avatar: z.file().max(2 * 1024 * 1024).mime(['image/png', 'image/jpeg']),
    }),
    handler: async ({ avatar }) => {
      const bytes = new Uint8Array(await avatar.arrayBuffer());
      const key = `avatars/${crypto.randomUUID()}-${avatar.name.replace(/[^\w.-]/g, '_')}`;
      await saveToStorage(key, bytes, avatar.type);
      return { name: avatar.name, key };
    },
  }),
};

async function saveToStorage(key: string, bytes: Uint8Array, type: string) {
  // upload to S3, R2 or similar here
}

z.file() is Zod 4’s file schema. .max() takes bytes and .mime() an allowlist of types. If either check fails, the action returns an input error before the handler runs; isInputError(result.error) gives you per-field messages. The random prefix stops two users overwriting each other’s files, and cleaning the name stops path tricks. Our Astro Actions validation tip shows how to display field errors.

Raise the body size limit

Action requests are capped at 1 MB by default. Anything larger fails before validation, so raise the limit to cover your largest allowed file:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  output: 'server',
  adapter: node({ mode: 'standalone' }),
  security: {
    actionBodySizeLimit: 5 * 1024 * 1024, // 5 MB
  },
});

Hosts add their own ceilings. Serverless functions commonly cap request bodies at a few megabytes, so for large files such as video, upload directly from the browser to storage with a presigned URL and send only the resulting key to Astro.

The endpoint alternative

Without Actions, read the form in an endpoint:

// src/pages/api/upload.ts
import type { APIRoute } from 'astro';

export const prerender = false;
const MAX = 2 * 1024 * 1024;
const TYPES = new Set(['image/png', 'image/jpeg']);

export const POST: APIRoute = async ({ request }) => {
  const form = await request.formData();
  const file = form.get('file');
  if (!(file instanceof File) || file.size === 0) {
    return new Response('No file', { status: 400 });
  }
  if (file.size > MAX || !TYPES.has(file.type)) {
    return new Response('File too large or wrong type', { status: 415 });
  }
  const bytes = new Uint8Array(await file.arrayBuffer());
  // ...store bytes
  return Response.json({ name: file.name, size: file.size }, { status: 201 });
};

file.type comes from the browser and can be faked. For images, check the first bytes (PNG starts with 89 50 4E 47, JPEG with FF D8 FF) or decode them before trusting the upload. See the API endpoints guide for more on request handling.

Cross-origin uploads

Astro’s security.checkOrigin rejects cross-site multipart/form-data posts to on-demand routes with a 403. Uploads from your own pages are same-origin and work. If another site must upload to yours, see CORS headers on Astro endpoints for the options.

Where to store files

Do not write uploads into public/ or the project folder. On serverless and edge platforms the file system is read-only or discarded between requests, and on a single server it mixes user content with your code. Use object storage (S3, Cloudflare R2, or your platform’s blob store) and save the returned key in your database. The Astro themes in our catalog are static, so uploads also require adding an adapter first.

FAQ

How do I upload a file in Astro?

Use a form with enctype="multipart/form-data" that posts to an Astro Action with accept: 'form', or to an endpoint that reads await request.formData(). The file arrives as a File object you can read with arrayBuffer().

Why does my Astro file upload fail for large files?

Action bodies are limited to 1 MB by default. Raise security.actionBodySizeLimit in astro.config.mjs, and check your host’s own request size limit.

How do I validate file type and size in Astro Actions?

Use z.file().max(bytes).mime([...types]) in the action’s input schema. Astro validates before the handler runs and returns input errors you can show next to the field.

Can I save uploaded files to the public folder?

No. public/ is copied at build time, and serverless file systems do not persist. Store files in object storage and serve them from there.