Skip to content

Fix import issue with Next.js 14 #272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions nextjs-end/next.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true,
}
};

module.exports = nextConfig;
8 changes: 4 additions & 4 deletions nextjs-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"lint": "next lint"
},
"dependencies": {
"@google-cloud/firestore": "^6.7.0",
"firebase": "^10.3.1",
"firebase-admin": "^11.10.1",
"next": "13.4.10",
"@google-cloud/firestore": "^6.8.0",
"firebase": "^10.7.2",
"firebase-admin": "^11.11.1",
"next": "^14.1.0",
"protobufjs": "^7.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
Expand Down
2 changes: 1 addition & 1 deletion nextjs-end/src/app/actions.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use server";

import { addReviewToRestaurant } from "@/src/lib/firebase/firestore.js";
import { getAuthenticatedAppForUser } from "@/src/lib/firebase/firebase";
import { getAuthenticatedAppForUser } from "@/src/lib/firebase/getAuthenticatedAppForUser.js";
import { getFirestore } from "firebase/firestore";

// This is a next.js server action, an alpha feature, so
Expand Down
7 changes: 2 additions & 5 deletions nextjs-end/src/app/layout.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "@/src/app/styles.css";
import Header from "@/src/components/Header.jsx";
import { getAuthenticatedAppForUser } from "@/src/lib/firebase/firebase";
import { getAuthenticatedAppForUser } from "@/src/lib/firebase/getAuthenticatedAppForUser.js";

// Force next.js to treat this route as server-side rendered
// Without this line, during the build process, next.js will treat this route as static and build a static HTML file for it
export const dynamic = "force-dynamic";
Expand All @@ -11,18 +12,14 @@ export const metadata = {
"FriendlyEats is a restaurant review website built with Next.js and Firebase.",
};


export default async function RootLayout({ children }) {
const { currentUser } = await getAuthenticatedAppForUser();
return (
<html lang="en">

<body>
<Header initialUser={currentUser?.toJSON()}/>

<main>{children}</main>
</body>

</html>
);
}
7 changes: 1 addition & 6 deletions nextjs-end/src/app/restaurant/[id]/page.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import Restaurant from "@/src/components/Restaurant.jsx";
import { useUser } from "@/src/lib/firebase/auth";
import {
getRestaurantById,
getReviewsByRestaurantId,
} from "@/src/lib/firebase/firestore.js";
import {
getAuthenticatedAppForUser
} from "@/src/lib/firebase/firebase.js";


import getAuthenticatedAppForUser from "@/src/lib/firebase/getAuthenticatedAppForUser.js";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import getAuthenticatedAppForUser from "@/src/lib/firebase/getAuthenticatedAppForUser.js";
import { getAuthenticatedAppForUser } from "@/src/lib/firebase/getAuthenticatedAppForUser.js";


export const dynamic = "force-dynamic";

Expand Down
4 changes: 1 addition & 3 deletions nextjs-end/src/components/Restaurant.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
// It receives data from src/app/restaurant/[id]/page.jsx

import { React, useState, useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import {
getRestaurantSnapshotById,
getReviewsSnapshotByRestaurantId,
} from "@/src/lib/firebase/firestore.js";
import { auth } from "@/src/lib/firebase/firebase.js";
import {getUser} from '@/src/lib/getUser'
import { getUser } from '@/src/lib/firebase/getUser'
import { updateRestaurantImage } from "@/src/lib/firebase/storage.js";
import ReviewDialog from "@/src/components/ReviewDialog.jsx";
import RestaurantDetails from "@/src/components/RestaurantDetails.jsx";
Expand Down
7 changes: 0 additions & 7 deletions nextjs-end/src/lib/firebase/config.js

This file was deleted.

82 changes: 0 additions & 82 deletions nextjs-end/src/lib/firebase/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,85 +22,3 @@ export const firebaseApp =
export const auth = getAuth(firebaseApp);
export const db = getFirestore(firebaseApp);
export const storage = getStorage(firebaseApp);


export async function getAuthenticatedAppForUser(session = null) {


if (typeof window !== "undefined") {
// client
console.log("client: ", firebaseApp);

return { app: firebaseApp, user: auth.currentUser.toJSON() };
}

const { initializeApp: initializeAdminApp, getApps: getAdminApps } = await import("firebase-admin/app");

const { getAuth: getAdminAuth } = await import("firebase-admin/auth");

const { credential } = await import("firebase-admin");

const ADMIN_APP_NAME = "firebase-frameworks";
const adminApp =
getAdminApps().find((it) => it.name === ADMIN_APP_NAME) ||
initializeAdminApp({
credential: credential.applicationDefault(),
}, ADMIN_APP_NAME);

const adminAuth = getAdminAuth(adminApp);
const noSessionReturn = { app: null, currentUser: null };


if (!session) {
// if no session cookie was passed, try to get from next/headers for app router
session = await getAppRouterSession();

if (!session) return noSessionReturn;
}

const decodedIdToken = await adminAuth.verifySessionCookie(session);

const app = initializeAuthenticatedApp(decodedIdToken.uid)
const auth = getAuth(app)

// handle revoked tokens
const isRevoked = !(await adminAuth
.verifySessionCookie(session, true)
.catch((e) => console.error(e.message)));
if (isRevoked) return noSessionReturn;

// authenticate with custom token
if (auth.currentUser?.uid !== decodedIdToken.uid) {
// TODO(jamesdaniels) get custom claims
const customToken = await adminAuth
.createCustomToken(decodedIdToken.uid)
.catch((e) => console.error(e.message));

if (!customToken) return noSessionReturn;

await signInWithCustomToken(auth, customToken);
}
console.log("server: ", app);
return { app, currentUser: auth.currentUser };
}

async function getAppRouterSession() {
// dynamically import to prevent import errors in pages router
const { cookies } = await import("next/headers");

try {
return cookies().get("__session")?.value;
} catch (error) {
// cookies() throws when called from pages router
return undefined;
}
}

function initializeAuthenticatedApp(uid) {
const random = Math.random().toString(36).split(".")[1];
const appName = `authenticated-context:${uid}:${random}`;

const app = initializeApp(firebaseConfig, appName);

return app;
}
77 changes: 77 additions & 0 deletions nextjs-end/src/lib/firebase/getAuthenticatedAppForUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { initializeApp } from "firebase/app";
import {
getAuth,
signInWithCustomToken,
} from "firebase/auth";
import { auth as firebaseAuth, firebaseApp, firebaseConfig } from "@/src/lib/firebase/firebase.js";

export async function getAuthenticatedAppForUser(session = null) {
if (typeof window !== 'undefined') {
// Running on the client
console.log("client: ", firebaseApp);
return { app: firebaseApp, user: firebaseAuth.currentUser.toJSON() };
}

const { initializeApp: initializeAdminApp, getApps: getAdminApps } = await import("firebase-admin/app");
const { getAuth: getAdminAuth } = await import("firebase-admin/auth");
const { credential } = await import("firebase-admin");

const ADMIN_APP_NAME = "firebase-frameworks";
const adminApp =
getAdminApps().find((it) => it.name === ADMIN_APP_NAME) ||
initializeAdminApp({
credential: credential.applicationDefault(),
}, ADMIN_APP_NAME);

const adminAuth = getAdminAuth(adminApp);
const noSessionReturn = { app: null, currentUser: null };

if (!session) {
// if no session cookie was passed, try to get from next/headers for app router
session = await getAppRouterSession();
if (!session) return noSessionReturn;
}

const decodedIdToken = await adminAuth.verifySessionCookie(session);
const app = initializeAuthenticatedApp(decodedIdToken.uid)
const auth = getAuth(app)

// handle revoked tokens
const isRevoked = !(await adminAuth
.verifySessionCookie(session, true)
.catch((e) => console.error(e.message)));
if (isRevoked) return noSessionReturn;

// authenticate with custom token
if (auth.currentUser?.uid !== decodedIdToken.uid) {
// TODO(jamesdaniels) get custom claims
const customToken = await adminAuth
.createCustomToken(decodedIdToken.uid)
.catch((e) => console.error(e.message));

if (!customToken) return noSessionReturn;
await signInWithCustomToken(auth, customToken);
}

console.log("server: ", app);
return { app, currentUser: auth.currentUser };
}

async function getAppRouterSession() {
// dynamically import to prevent import errors in pages router
const { cookies } = await import("next/headers");

try {
return cookies().get("__session")?.value;
} catch (error) {
// cookies() throws when called from pages router
return undefined;
}
}

function initializeAuthenticatedApp(uid) {
const random = Math.random().toString(36).split(".")[1];
const appName = `authenticated-context:${uid}:${random}`;
const app = initializeApp(firebaseConfig, appName);
return app;
}
File renamed without changes.