Skip to Content

Astro Integration

This guide explains how to integrate FileZen with Astro applications. We recommend using our dedicated SDK packages for the best experience.

📁 Code Example: View the complete working example at github.com/FileZen/filezen/tree/main/apps/astro-app 

Installation

Install the required FileZen packages for an Astro project:

Setup

1. Environment Configuration

Set your FileZen API key as an environment variable. This can be done in your local .env file during development or as a system environment variable in production.

.env
FILEZEN_API_KEY=your_api_key_here

The FileZen SDK automatically detects the FILEZEN_API_KEY environment variable for server-side operations, so no additional configuration is needed in your API routes.

2. Astro Configuration

Configure your astro.config.mjs to enable server-side rendering for API routes:

astro.config.mjs
import { defineConfig } from 'astro/config'; export default defineConfig({ output: 'server', // Enable server-side rendering for API routes });

3. API Route

The API route is crucial for security, as it keeps your API key on the server and prevents it from being exposed in the client-side code.

Create an API route to handle file uploads and other operations. The createZenAstroRouter function from @filezen/astro simplifies this process by creating the necessary POST and DELETE handlers.

src/pages/api/upload.ts
import { ZenApi } from '@filezen/js'; import { createZenAstroRouter } from '@filezen/astro'; import type { APIContext } from 'astro'; // The ZenApi class will automatically pick up the FILEZEN_API_KEY from environment variables. const zenApi = new ZenApi(); export const { POST, DELETE } = createZenAstroRouter(zenApi);

By default, the client expects this route at /api/upload. You should create this file at src/pages/api/upload.ts. If you wish to use a different path, you can create the route file elsewhere and specify the new path when initializing the ZenClient.

Request Validation Middleware (Optional)

You can add request validation middleware to verify requests before generating signed URLs for file uploads. This is useful for implementing authentication, authorization, or other custom validation logic.

src/pages/api/upload.ts
import { ZenApi, ZenError } from '@filezen/js'; import { createZenAstroRouter } from '@filezen/astro'; import type { APIContext } from 'astro'; const zenApi = new ZenApi(); const requestMiddleware = async (context: APIContext) => { /** * Here you can verify request, e.g - check user authentication: * const user = await getUserFromRequest(context); * if (!user) { * throw new ZenError(401, 'Unauthorized'); * } * return { userId: user.id } */ }; export const { POST, DELETE } = createZenAstroRouter(zenApi, { onRequest: requestMiddleware, });

The middleware function can:

  • Return additional metadata that will be available in the request context
  • Throw a ZenError to reject the request with a specific status code and message
  • Return void or undefined if no additional processing is needed

Using FileZen in Astro

Astro provides multiple ways to integrate FileZen, depending on your needs. You can use pure Astro components with client-side scripts or React components for more complex interactions.

Pure Astro Component Example

Create a pure Astro component that handles file uploads using client-side JavaScript:

src/components/FileUpload.astro
--- // Pure Astro component for file uploads --- <div> <input type="file" id="file-input" accept="image/*" /> <div id="result"></div> <div id="error"></div> </div> <script> import { ZenClient } from '@filezen/js'; const zenClient = new ZenClient(); const fileInput = document.getElementById('file-input'); const result = document.getElementById('result'); const error = document.getElementById('error'); async function handleUpload(file) { try { const uploadResult = await zenClient.upload(file); if (uploadResult.error) { error.textContent = uploadResult.error.message; return; } result.innerHTML = `<p>Upload successful: ${uploadResult.file?.url}</p>`; error.textContent = ''; } catch (err) { error.textContent = 'Upload failed'; } } fileInput?.addEventListener('change', (event) => { const file = event.target.files?.[0]; if (file) { handleUpload(file); } }); </script>

React Component in Astro

For more complex interactions, you can use React components within Astro. Here is a minimal example:

src/components/FileUploadReact.tsx
import { ZenClient } from '@filezen/js'; import { useRef, useState } from 'react'; const zenClient = new ZenClient(); export default function FileUploadReact() { const [result, setResult] = useState(''); const [error, setError] = useState(''); const fileInputRef = useRef(null); const handleChange = async (event) => { const file = event.target.files?.[0]; if (!file) return; setError(''); setResult(''); try { const uploadResult = await zenClient.upload(file); if (uploadResult.error) { setError(uploadResult.error.message); return; } setResult(`Upload successful: ${uploadResult.file?.url}`); } catch { setError('Upload failed'); } }; return ( <div> <input type="file" ref={fileInputRef} onChange={handleChange} accept="image/*" /> {result && <div>{result}</div>} {error && <div>{error}</div>} </div> ); }

Using Components in Astro Pages

Use your components in Astro pages:

src/pages/index.astro
--- import Layout from '@/layouts/Layout.astro'; import FileUpload from '@/components/FileUpload.astro'; import FileUploadReact from '@/components/FileUploadReact'; --- <Layout title="FileZen Astro Example"> <div class="container"> <div class="header"> <h1>FileZen Upload Example</h1> <p> This example demonstrates how to use FileZen for file uploads with <a href="https://astro.build" target="_blank" rel="noopener noreferrer">Astro</a>. The upload is handled with API routes and server-side processing. </p> </div> <div class="components-grid"> <div class="component-section"> <h2>Pure Astro Component</h2> <FileUpload /> </div> <div class="component-section"> <h2>React Component in Astro</h2> <FileUploadReact client:load /> </div> </div> </div> </Layout> <style> .components-grid { display: grid; grid-template-columns: 1fr; gap: 3rem; margin-bottom: 3rem; } .component-section { border: 1px solid #374151; border-radius: 1rem; padding: 2rem; background: rgba(31, 41, 55, 0.3); } .component-section h2 { font-size: 1.5rem; font-weight: 600; color: #f9fafb; margin-bottom: 1.5rem; text-align: center; border-bottom: 1px solid #374151; padding-bottom: 1rem; } @media (min-width: 768px) { .components-grid { grid-template-columns: 1fr 1fr; } } </style>

The zenClient.upload() method requests a signed URL from your API route (/api/upload), then uploads the file directly to FileZen from the client side. This reduces traffic usage on your server since files don’t pass through your backend.

Last updated on
© 2026 FileZen. All rights reserved.