I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way.

Initialization of Firebase Admin SDK

// firebase.js
import * as admin from "firebase-admin";
import serviceAccount from "./firebase.serviceAccount.json";

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL
    });
}

const firestore = admin.firestore();
const storage = admin.storage();

c
export { firestore, storage };

Process for Uploading Image

// route.js
import {  storage } from "../../firebase";

const router = async (req, res) => {
    // ...
    // Retrieving file from API request and so forth...
    // ...

    const file = <an instance of File object>;

    const currentTime = Date.now();
    const fileName = file.name;

    const fileTitle = `${currentTime}-${fileName}`;

    const metadata = {
         contentType: file.type
    };

    const task = storage.ref().child(fileTitle).put(file, metadata);

    task.then(snapshot => snapshot.ref.getDownloadURL())
        .then(console.log)
        .catch(console.error);

};

export default router;


Error Encounter

Encountered an error while importing the Cloud Storage client library for Node.js. Ensure that you have installed the "@google-cloud/storage" npm package correctly. Original error: Error: EIO: i/o error, read

Even though @google-cloud/storage is listed in my package dependencies

Answer №1

  1. Insert storageBucket into your admin.initializeApp({})
if (!admin.apps.length) {
  try {
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
      storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    });
  } catch (e) {
    console.log("Failed to initialize App: " + e);
  }
}
  1. Replace admin.storage() with admin.storage().bucket()
import * as admin from "firebase-admin";
import serviceAccount from "./firebase.serviceAccount.json";

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL
    });
}

const firestore = admin.firestore();
const storage = admin.storage().bucket();

export { firestore, storage };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an issue trying to access undefined properties in the mongoose response object

When utilizing the mongoose Schema in node.js, I have defined the following structure: mongoose.Schema({ name: { type: String, required: true }, userId: { type: String }, water: { type: Array }, fertilizer: { type: Array } }) Subsequently, ...

What is the method for locating a sentence enclosed by asterisks to emphasize the text within my markup language?

My current task involves developing a component that can render text in posts or comments. This component uses regex to detect mentions, hashtags, and URLs. One of the requirements is to identify text enclosed within pairs of asterisks so that it can be di ...

AngularJS - Unchecked radio button issue

Within my code, there is an ng-repeat including several radio buttons: <div class="panel panel-default" ng-repeat="item in vm.itemList"> ... <td ng-show="item.edit"> <div class="row"> ...

Switching Column Content with jQuery on Mobile Devices

In my design, I have a dynamic two-column layout created using Twitter Bootstrap 3. The layout switches between image-text and text-image alignment for each row. The goal is to adjust it for smaller screens (less than 768px) so that rows with images on th ...

Discover the secrets to replicating the mesmerizing horizontal scrolling menu akin to the

What is the most effective way to create a horizontal menu similar to the innovative Google picture menu? Could someone kindly share their knowledge and provide the code for achieving the same outcome? ...

Error encountered during deployment of Cloud Functions due to missing dependencies in monorepository

I am facing an issue with my monorepo setup where my cloud functions are importing from another package within the workspace. The imported package is listed in the package.json under devDependencies as shown below: // stuff "dependencies": { &q ...

React: State does not properly update following AJAX request

I'm currently facing a challenge in my React project where I need to make two AJAX calls and update the UI based on the data received. Below is the implementation of my render method: render() { if (this.state.examsLoaded) { return ( ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

Utilizing Socket.io and SailsJS for a Chat Application: Detecting Client Shutdown and Updating User Status to Offline

I'm currently developing a multi-user chat application using node-webkit and SailJs, and I've been working on implementing the login status of users. When a user opens the application, they are considered online. The scenarios in which a user wou ...

How Axios triggers CanceledError using Abort controller in a React application

I have created a custom axios instance with interceptors to handle authentication requests. The customized axios instance looks like this: const BASE_URL = 'http://localhost:8000'; export const axiosPrivate = axios.create({ baseURL: BASE_URL, ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

Nextjs 12.2 now offers the option to include custom headers prior to making API route requests

Can a middleware or other structure be used to set custom headers for a request before it is sent via api routes? I am working with Next.js 12.2 and need to add authorization headers to many existing requests in the project. I am looking for a way to crea ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Issue with sending events to Firebase Analytics platform from the web

Database Version: 12.5.0 Project: React Native with Redux How I'm querying: const fetchUserData = useCallback( (userId: string) => { if (typeof window !== "undefined") { database().fetchData(userId) } }, [] ) What the Databas ...

Issues with locating the fonts: React-slick paired with nextjs

Incorporating react-slick into a NextJs project has been quite seamless, however, I'm encountering issues with importing the necessary fonts from the CSS files. To address this snag, I've attempted the following steps: npm install slick-carouse ...

Is there a way to verify if the password entered by the user matches the input provided in the old password field?

I am trying to compare the user's password with the one entered in the "oldPassword" input field. The challenge is hashing the input from the "oldPassword" field for comparison. How can I achieve this? Please review my ejs file and suggest improvement ...

Is there a hierarchy to be followed within the <head> element?

I have been developing websites using HTML for nearly 3 years now, but since I had to teach myself, there are still a few things I am unsure about. One question that has recently become important is whether it is possible to create groups within the <h ...

In a production environment, an ENOENT error in Next.js was triggered by fs.readdirSync

Utilizing the Next.js App Router, I attempted to retrieve all my markdown posts stored in files by scanning a directory using fs.readdirSync(). While everything worked flawlessly locally, upon deploying on Vercel, an unexpected issue arose. The code was e ...