Firebase Storage
Firebase Storage
The PluginFirebaseStorage adapter uploads files to Firebase Cloud Storage using the Firebase SDK. It integrates seamlessly with Firebase Authentication for secure uploads.
Installation
Install the Firebase SDK:
pnpm add firebase
Setup
Initialize Firebase in your Nuxt app:
import { initializeApp } from "firebase/app"
import { getStorage } from "firebase/storage"
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
}
export const app = initializeApp(firebaseConfig)
export const storage = getStorage(app)
Usage
import { PluginFirebaseStorage } from "nuxt-upload-kit/providers/firebase"
import { storage } from "~/plugins/firebase.client"
const uploader = useUploadKit({
storage: PluginFirebaseStorage({
storage,
path: "uploads",
}),
})
nuxt-upload-kit/providers/firebase to avoid bundling the Firebase SDK for users who don't need it.Options
| Option | Type | Required | Description |
|---|---|---|---|
storage | FirebaseStorage | Yes | Firebase Storage instance |
path | string | No | Folder path for uploads |
customMetadata | Record<string, string> | No | Custom metadata for files |
cacheControl | string | No | Cache-Control header |
contentDisposition | string | No | Content-Disposition header |
Authentication
Firebase Storage uses Firebase Authentication. Ensure users are signed in before uploading:
import { getAuth, signInWithEmailAndPassword } from "firebase/auth"
const auth = getAuth()
await signInWithEmailAndPassword(auth, email, password)
// Now uploads will work with authenticated user
Storage Rules
Configure Firebase Storage rules to control access:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
// Public read, authenticated write
match /uploads/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
// User-specific folders
match /users/{userId}/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null && request.auth.uid == userId;
}
}
}
Folder Organization
Static Path
PluginFirebaseStorage({
storage,
path: "uploads/images",
})
// Files go to: uploads/images/{fileId}
Dynamic Path (Per User)
import { getAuth } from "firebase/auth"
const auth = getAuth()
const userId = auth.currentUser?.uid
const uploader = useUploadKit({
storage: PluginFirebaseStorage({
storage,
path: `users/${userId}/uploads`,
}),
})
Date-Based Path
const date = new Date().toISOString().split("T")[0] // 2024-01-15
const uploader = useUploadKit({
storage: PluginFirebaseStorage({
storage,
path: `uploads/${date}`,
}),
})
Custom Metadata
Attach metadata to uploaded files:
PluginFirebaseStorage({
storage,
path: "uploads",
customMetadata: {
uploadedBy: "user123",
application: "my-app",
},
})
The adapter automatically adds:
originalName- Original filenamesize- File size in bytes
Cache Control
Set caching headers for uploaded files:
PluginFirebaseStorage({
storage,
path: "uploads",
cacheControl: "public, max-age=31536000", // 1 year
})
Upload Result
After successful upload, file.uploadResult contains:
{
url: 'https://firebasestorage.googleapis.com/v0/b/...',
storageKey: 'uploads/abc123.jpg',
bucket: 'your-project.appspot.com',
generation: '1234567890',
md5Hash: 'abc123...'
}
Complete Example
import { PluginFirebaseStorage } from "nuxt-upload-kit/providers/firebase"
import { getStorage } from "firebase/storage"
import { getAuth } from "firebase/auth"
const storage = getStorage()
const auth = getAuth()
const uploader = useUploadKit({
storage: PluginFirebaseStorage({
storage,
path: `users/${auth.currentUser?.uid}/uploads`,
customMetadata: {
source: "web-app",
},
cacheControl: "public, max-age=86400",
}),
// Combine with other plugins
thumbnails: true,
imageCompression: { quality: 0.8 },
maxFileSize: 10 * 1024 * 1024, // 10MB
})
// Listen for uploads
uploader.on("upload:complete", (files) => {
files.forEach((file) => {
console.log("Uploaded:", file.uploadResult.url)
})
})
Standalone Upload
Upload raw Blob or File data directly, bypassing the useUploadKit pipeline:
const storage = PluginFirebaseStorage({
storage,
path: "uploads",
})
// Upload an edited image
const croppedBlob = await getCroppedCanvas().toBlob()
const result = await storage.upload(croppedBlob, "edited-photo.jpg", {
contentType: "image/jpeg",
})
console.log(result.url) // https://firebasestorage.googleapis.com/...
console.log(result.storageKey) // uploads/edited-photo.jpg
The path prefix is automatically applied to the storage key.
Deleting Files
When you call removeFile(), the adapter deletes from Firebase:
await uploader.removeFile(file.id)
Loading Existing Files
Load previously uploaded files:
await uploader.initializeExistingFiles([
{ id: "uploads/file1.jpg" },
{ id: "uploads/file2.png" },
])
The adapter fetches metadata and download URLs from Firebase.
Troubleshooting
"storage/unauthorized"
The user doesn't have permission. Check:
- User is authenticated
- Storage rules allow the operation
- The path matches your rules
"storage/quota-exceeded"
You've exceeded Firebase Storage quota. Check your Firebase Console for usage.
"storage/invalid-checksum"
File was corrupted during upload. Try uploading again.
CORS Errors
If accessing files from a different domain, configure CORS:
gsutil cors set cors.json gs://your-bucket-name
[
{
"origin": ["https://your-domain.com"],
"method": ["GET", "HEAD"],
"maxAgeSeconds": 3600
}
]
Firebase Emulator
For local development, use the Firebase Emulator:
import { connectStorageEmulator } from "firebase/storage"
if (process.dev) {
connectStorageEmulator(storage, "localhost", 9199)
}

