Utilizing Firebase authentication and next-auth in Next.js - Authentication currently returns null

I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase

Here is the firebase configuration:

import { initializeApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
    measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const firebase_app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
const auth = getAuth(firebase_app);
export { firebase_app, auth }

The issue I'm facing is that although I can sign in successfully, when attempting to utilize auth from firebase, it returns null/undefined.

Below is the code snippet for updating the password:

import { NextResponse } from 'next/server'
import { EmailAuthProvider, updatePassword, reauthenticateWithCredential } from "firebase/auth";
import { auth} from '@/firebase/config'

export async function POST(request: Request) {
    const res = await request.formData()
    const old_password = res.get('old-password')?.toString()
    const new_password = res.get('new-password')?.toString()
    const confirm_password = res.get('confirm-password')?.toString()
    const user = auth.currentUser;
    console.log("user: ", user)

    if(!old_password || !new_password || !confirm_password) {
        return NextResponse.json({ status: 400, statusText: "Missing info" })
    }
    else if(new_password !== confirm_password) {
        return NextResponse.json({ status: 400, statusText: "Passwords do not match" })
    }

    if(user != null){
        const userEmail = user.email || "";
        const credential = EmailAuthProvider.credential(userEmail, old_password);

        reauthenticateWithCredential(user, credential).then(() => {
            // User re-authenticated.
            updatePassword(user, new_password).then(() => {
                // Update successful.
                return NextResponse.json({ status: 200, statusText: "Password updated" })
              }).catch((error) => {
                // An error ocurred
                return NextResponse.json({ status: 500, statusText: "Error updating password" })
              });
          }).catch((error) => {
            // An error ocurred
            if(error.code === "auth/wrong-password"){
                throw new Error("wrong-password");
            }
            else{
                throw new Error("error-reauthenticating");
            }
            //return NextResponse.json({ status: 401, statusText: "Incorrect password" })
        });
    }
    else{
        // If not logged in, redirect to login page
        return NextResponse.json({ status: 401, statusText: "Not logged in" })
    } 
}

Would it be advisable to discontinue using next-auth? Alternatively, are there other potential solutions?

Answer №1

It is common for Firebase to require some time to validate tokens, resulting in getAuth() returning null at startup. To ensure proper authentication tracking, utilize onAuthStateChanged.

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

AngularJS encounters bad configuration on 'GET' request

I am facing an issue with my API that returns data to AngularJS based on a given ID. When the data is returned as JSON, AngularJS throws a 'badcfg' error, indicating that it could be due to the format of the returned data. I'm struggling to ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...

A ReactJS Error occurred: {error: 400, reason: "Failed match", message: "Failed match [400]", errorType: "Meteor.Error"}

I encountered an issue while attempting to send form data to the server when clicking on the Next Button in a Wizard Form. The error that occurs is related to an "Undefined User" warning displayed in the Console during Step 1 of the form submission: " { ...

perform a JSON request in a RESTful manner

Can you explain the concept of making a RESTful JSON request? In the given scenario, when Backbone attempts to read or save a model to the server, it calls upon the function known as Backbone.sync. This function, by default, utilizes (jQuery/Zepto).ajax t ...

Utilizing NodeJS code and the SlackAPI to build a custom chatbot named PFBot

Recently, I came up with an idea for a Slack Bot that could censor inappropriate language used by users. For example, if a user types a curse word, the bot would automatically replace it with symbols based on the length of the word. Although I'm rela ...

What is the best way to transfer data from one function to another file in React without directly calling the component or using props?

filename - Header.jsx import { useEffect, useState } from 'react' import { getValue } from './Input' import TextField from '@mui/material/TextField'; export const Header = () => { const [search, setSearch] = useState( ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...

AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format: {"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","u ...

Struggling with the addition of the 'Other' option in React manually. Any tips or suggestions?

I've encountered a slight issue regarding the functionality of my React Component below. Specifically, I want users to have the ability to enter a poll category that is not listed in the select component options by using an input field. This scenario ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

The AJAX request and UPDATE query are not working as expected

Currently, I am attempting to use an UPDATE query with an AJAX call to update a player's division by sending it to the update_divisions.php file. The process involves selecting a user from one select box and choosing the desired division from another ...

Is there a way to trigger an interact.js event that will reset all draggables back to their original position at coordinates (0, 0)?

I am trying to figure out how to trigger an onmove or drag move event to reset the position of a draggable div to x:0 y: 0. Despite looking at various sources like help topics here and on interact.js main page, I haven't found the right solution yet. ...

Error Alert: Attempting to access the 'prototype' property of an undefined value has resulted in a TypeError after switching to react-scripts version 4.0.3

I encountered a problem where I received the following error message: (Uncaught Error: Module build failed (from ./node_modules/source-map-loader/dist/cjs.js)). After attempting to resolve it by using npm install, a new error popped up in the console: path ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

What is the best way to switch a Boolean value in React Native?

Struggling with toggling a Boolean state from true to false when the result is undefined. Tried several methods but none seem to work. The boolean state in the constructor is defined like this: class UserInfo extends Component{ constructor(props){ s ...

Determine the hue of a specific location on a geometric surface

I'm currently working with THREE.js for my scene rendering and I have a complex question - how can I retrieve the color of a specific point on a geometry face? When I mention color, it's not just the face or material color that I'm interest ...

Adding a class to a TD element only when there is text in that TD as well as in other TD elements

I am facing a challenge where I need to add a new class to a td element, specifically the first one in the code snippet below. However, this should only happen if that td contains a certain number (e.g., "2") and if the next td contains some specific text ...