•  


Fix import issue with Next.js 14 by spiffylogic · Pull Request #272 · firebase/friendlyeats-web · GitHub
Skip to content
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

Fix import issue with Next.js 14 #272

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Fix import issue with Next.js 14, and tidy up
  • Loading branch information
spiffylogic committed Jan 28, 2024
commit 46f788ff9fd423660d1ec617dcc50041b978f3f7
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";

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;
}
- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본