Uploading images to firebase storage with node.js

Search for a command to run...

how can i upload this to github, i cannot set env variable in json file and i want to upload my project on git. using key.json way wont allow me to that, please help.
Piyush Garg Hi,
I followed your instructions, but I didn't get the link like you did
I don't know if I did something wrong, because the link above doesn't return the image, it just says not found
Hope you can help me
Thanks
Trung
Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...

Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript. https://youtu.be/lKe57l8sttw Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE...

Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless. So, let's get started. Step 1. Create an AWS Account ☁️ In order to deploy functions to AWS Lambda, you should have a...

Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...

Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding.
So, let's get started.
In this step, we would create a project on the firebase console. Navigate to https://firebase.google.com/ and log in with your Google account. It's absolutely free and no credit card required. After logging in, create a project in firebase, and enter any project name of your choice, once done click on submit and wait for the project to finish building up. Now, you would see a dashboard something like this

Great, now click on the setting icons and navigate to project settings as shown in the following image.

In project settings, navigate to the service accounts tab to download our credentials.

In service accounts, click on the Generate new private key button to generate your key.

Now, your credentials.json would be downloaded to your machine. Copy this file to your project folder where we are now going to build the project.
Great, as you have successfully set up your firebase account, now let's write some code.
Firstly, init your project by running the following command:
npm init -y
Great, now install the following dependencies.
npm install firebase-admin uuidGreat, now fire up your favorite code editor. (vs-code) and code along with me.
const firebaseAdmin = require('firebase-admin');
const { v4: uuidv4 } = require('uuid');
// change the path of json file
const serviceAccount = require('./hashnode-dev-c6f91-firebase-adminsdk-20fsu-2d218c1c69.json');
const admin = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
});
const storageRef = admin.storage().bucket(`gs://hashnode-dev-c6f91.appspot.com`);
.bucket() function accepts the bucket name as a parameter. To get your bucket name, open the firebase dashboard, navigate to the Storage tab, and then click on Get started.


After clicking on Get started, firebase will ask you cloud storage location, you can go with default storage.

Now, copy the bucket name of your storage.

and then create a firebase storage refrence. (As we did earlier)
const storageRef = admin.storage().bucket(`gs://hashnode-dev-c6f91.appspot.com`);
Now, create a simple function uploadFile that accepts filePath and fileName as params, and uploads the file to the firebase storage.
async function uploadFile(path, filename) {
return storageRef.upload(path, {
public: true,
destination: `/uploads/hashnode/${filename}`,
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
}
});
}
Great, now let's test our function.
(async() => {
await uploadFile('./mypic.png', "my-image.png");
})();
Let's start the server: node index.js.
As you can see, my image file is successfully uploaded 🚀.

So far, we have successfully uploaded the file to firebase storage, but we don't have a public URL that is shareable and downloadable. So, let's add some code and implement this.
In order to share the public URL, we need to change some rules in the Firebase dashboard. In the Storage tab, navigate to the Rules tab and change the default rule to the rule pasted below.


rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
Great, Now inside the uploadFile function, Add the below code that is responsible for generating a public URL.
Updated uploadFile function:
async function uploadFile(path, filename) {
// Upload the File
const storage = await storageRef.upload(path, {
public: true,
destination: `/uploads/hashnode/${filename}`,
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
}
});
return storage[0].metadata.mediaLink;
}
Let's test our implementation
(async() => {
const url = await uploadFile('./mypic.png', "my-image.png");
console.log(url);
})();
Run the server: node index.js

As you can see, I got my link to download the file.
// index.js
const firebaseAdmin = require('firebase-admin');
const { v4: uuidv4 } = require('uuid');
const serviceAccount = require('./hashnode-dev-c6f91-firebase-adminsdk-20fsu-2d218c1c69.json');
const admin = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
});
const storageRef = admin.storage().bucket(`gs://hashnode-dev-c6f91.appspot.com`);
async function uploadFile(path, filename) {
// Upload the File
const storage = await storageRef.upload(path, {
public: true,
destination: `/uploads/hashnode/${filename}`,
metadata: {
firebaseStorageDownloadTokens: uuidv4(),
}
});
return storage[0].metadata.mediaLink;
}
(async() => {
const url = await uploadFile('./mypic.png', "my-image.png");
console.log(url);
})();
Thank you for reading. Happy Learning 🚀.