Using Firebase Storage for Documents, Images, and more
LaunchFa.st provides you with the APIs to interact with Firebase Storage, built on top of Web Standards.
src/pages/api/storage
directory. src/routes/api/storage/+server.ts
file. - Update the
firebaseConfig.ts
file to have the necessary variables for Firebase Storage:
-
In the Firebase console, open Settings > Service Accounts
-
Click Generate New Private Key, then confirm by clicking Generate Key
-
Securely store the JSON file containing the key
-
In the Firebase Console, Go to Storage, and save the value starting with gs://…
-
Update the JSON with the key storageBucket with the value obtained above
// Example firebase config, do
// make sure to add the storageBucket
// from the steps above
export default {
type: 'service_account',
project_id: '...',
private_key_id: '...',
private_key: '...',
client_email: '...',
client_id: '...',
auth_uri: '...',
token_uri: '...',
auth_provider_x509_cert_url: '...',
client_x509_cert_url: '...',
universe_domain: '...',
storageBucket: '...',
}
- To make it easier for you to implement file upload, just import the following component in your Svelte app:
---
// File: page.astro
import Upload from '@/components/Upload.astro'
---
<Upload />
<script lang="ts">
// File: +page.svelte
import Upload from '@/components/Upload.svelte'
</script>
<Upload />
- To fetch the uploaded file, make sure to persist the response containing the
fileURL
which’ll be used to fetch the original file. To do so, hit the following API:
---
// File: page.astro
---
<script>
const getFile = new URL('/api/storage/post', window.location.origin)
getFile.searchParams.set('file', fileURL)
fetch(getFile.toString())
.then((res) => res.json())
.then((res) => {
const { filePublicURL } = res
console.log(filePublicURL)
})
</script>
<script lang="ts">
// File: +page.svelte
import { onMount } from 'svelte'
const getFile = new URL('/api/storage', window.location.origin)
getFile.searchParams.set('file', fileURL)
onMount(() => {
fetch(getFile.toString())
.then((res) => res.json())
.then((res) => {
const { filePublicURL } = res
console.log(filePublicURL)
})
})
</script>