Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload images to Firebase.

I came across some helpful answers on Stack Overflow regarding this issue: Here is the link

Unfortunately, none of the suggested solutions have worked for me, as I keep receiving the following error:


FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
Bad Request

Below is the code snippet that I have been working on:

import Image from "next/image";
import { useSession } from "next-auth/react";
import { FaceSmileIcon } from "@heroicons/react/24/outline";
...
<Code continues here>
...
    

Despite my best efforts to troubleshoot and find a solution independently, I have not been successful. Any assistance or guidance would be greatly appreciated, as I am at a loss for what might be causing this issue.

In addition to implementing suggestions from other users, I also attempted to explicitly assign storage using getStorage() before the relevant line of code but without success:

.then((document) => {
   if(imageToPost) {
      const storage = getStorage();
      const storageRef = ref(storage, `posts/${document.id}`);

<More code included>

For reference, here is the content of my 'firebase.js' file:

import { initializeApp } from 'firebase/app';
import { getStorage } from "firebase/storage";

const firebaseConfig = {
    apiKey: "APIKEY-HERE",
    authDomain: "AUTHDOMAIN-HERE",
...
<Configuration details continue>
...

  export { db, storage };

Answer №1

Here's a solution that worked well for me using Firebase version 9.0.0:

addDoc(dbInstance, {
      message: inputRef.current.value,
      name: session?.user?.name,
      email: session?.user?.email,
      image: session?.user?.image,
      timestamp: serverTimestamp(),
    }).then((doc) => {
      if (imageToPost) {
        const storageRef = ref(storage, `posts/${doc.id}`);

        uploadString(storageRef, imageToPost, "data_url").then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            addDoc(dbInstance, { postImage: url });
          });
        });

        removeImage();
      }
    });

    inputRef.current.value = "";

Answer №2

Give this a try using Firebase version 8.6.3.

const docRef = firebase.firestore().collection("colection_name").doc();
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child('/posts/' + imageToPost.name).put(imageToPost);
console.log(uploadTask)
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
    (snapshot) => {
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
            case firebase.storage.TaskState.PAUSED:
                console.log('Upload is paused');
                break;
            case firebase.storage.TaskState.RUNNING:
                console.log('Upload is running');
                break;
        }
    },
    (error) => {
        switch (error.code) {
            case 'storage/unauthorized':
                // User doesn't have permission to access the object
                break;
            case 'storage/canceled':
                // User canceled the upload
                break;

            // ...

            case 'storage/unknown':
                // Unknown error occurred, inspect error.serverResponse
                break;
        }
    },
    () => {
        uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
            console.log('File available at', downloadURL);
            docRef.set({
                message: inputRef.current.value,
                name: session.user.name,
                email: session.user.email,
                image: downloadURL,
            });
        });
    }
);

If you're not interested in the upload progress and errors, you can skip that part of the code and directly proceed to getDownloadURL.

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

What causes the consistent filling of responses in jQuery ajax?

After observing that the response of an ajax call using jQuery is never empty, I have come across the following code snippet: $.ajax({ type: "get", data: { data }, url: "phpFile", datatype: 'text' }).done(functio ...

Having difficulty adding multiple items to the state array

I am currently working on a parent component that iterates over an array and passes props to a child component. In the child component (shown below), I have checkboxes with Font Awesome icons for users to mark their selections. When a user checks a box, I ...

Looking for a Hack to Integrate a Music Player into Your Website?

Currently, I am utilizing the Jplayer plugin from JQuery to incorporate an Audio player into my website. I have come across a situation where: If the user is not currently listening to any music while browsing the website, the page can load without any i ...

Navigating through intricate JavaScript objects

I am working with an object that looks like this: var obj = { "00a9": ["\u00A9", ["copyright"]], "00ae": ["\u00AE", ["registered"]], "203c": ["\u203C" ...

Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript: setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) { let octdctruns: OctDctRun[] = [...this.octDctRuns]; const index = octdctruns.findIndex((o) => o.guid ...

The GraphQl Code Generator fails to correctly generate the graphql() function in Next.js applications

While working on my next.js project, I integrated GraphQL to generate types for queries. However, the code generator is not functioning properly and displaying an error message: "The query argument is unknown! Please regenerate the types." within the gql.t ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...

Encountering a 404 error while trying to use the autolinker

I have been struggling with this issue for the past day and can't seem to solve it on my own. Essentially, I am attempting to use Autolinker.js to automatically convert URLs into clickable hyperlinks in my chat application. However, every time I try ...

Utilizing functions instead of classes in Next.js custom document when using Styled Components: A step-by-step guide

For my project, I decided to use NextJS along with Styled Components. Upon referring to the documentation provided in the link below, I integrated a custom _document.js file in NextJS to ensure that Styled Components function correctly. Here is the Styled ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

The addition of an asynchronous call caused Array.map to start experiencing errors

I am working on a React component that iterates through an array of messages and renders JSX based on certain conditions: messages.map(async (msg) => { let previewImage: URL | undefined = undefined; if (msg.mediaId) { previewImage = await stora ...

Tips for preventing the caret (^) symbol from being added to a package when installing with yarn

Is there a way to prevent Yarn from adding the caret prefix to version numbers when installing packages like npm has for changing version prefix (https://docs.npmjs.com/misc/config#save-prefix)? I would like to apply this configuration only for the current ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Having trouble with the installation of [email protected] on Windows 10 x64?

I am currently in the process of setting up hiredis on my Windows 64-bit operating system as it is a requirement for the node-celery package. My system specifications are as follows: Node v7.9.0 npm v4.5.0 Visual Studio Community 2013 with Update 5 (en_ ...

Sending a batch of files through an axios request by passing them as an object

I need to send multiple images in a specific format through an API call { "date":"currentDate", "files":[Files uploaded via input box] } Here is my approach: Method 1 const event = document.querySelector("#files"); const f ...

The error "localStorage is not defined when using an axios interceptor in NextJS"

Within my root directory, there lies a file named api.js. This particular file is responsible for managing calls to an external API, with a focus on request and response interceptors. One specific use case involves injecting the access_token, leading to th ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

Display an alert when no matches are found in autocomplete suggestions

I am implementing the code below to populate a textbox with data. If I input a, all records starting with a are displayed in the dropdown from the database. However, if I input a value that does not exist in the database, there is no message like "No Recor ...

Discover the name of a color using its HEX code or RGB values

Is there a way to retrieve the color name from RBG or HEX code using JavaScript or JQuery? Take for instance: Color Name RGB black #000000 white #FFFFFF red #FF0000 green #008000 ...