Next.js中firebaseAdmin验权接口报fs模块未找到错误的解决方法
修复“Module not found: Can't resolve 'fs'”错误
1. 修正getServerSideProps的位置
Next.js 中getServerSideProps仅能直接导出在pages目录下的页面组件文件中,不能放在普通包装组件(如你的ProtectedRoute)内。如果需要复用权限验证逻辑,可将验证代码抽成独立函数,在每个需要保护的页面的getServerSideProps中调用:
示例:抽离验证函数
新建utils/verifyAuth.ts:
import nookies from 'nookies'; import { firebaseAdmin } from '../firebaseAdmin'; import { GetServerSidePropsContext } from 'next'; export async function verifyAuth(ctx: GetServerSidePropsContext) { const cookies = nookies.get(ctx); try { await firebaseAdmin.auth().verifyIdToken(cookies.token); } catch (err) { // 验证失败时重定向到登录页 ctx.res.writeHead(302, { Location: '/login' }); ctx.res.end(); return { props: {} }; } }
在页面组件中使用
比如pages/protected-page.tsx:
import ProtectedRoute from '../components/ProtectedRoute'; import { verifyAuth } from '../utils/verifyAuth'; import { GetServerSidePropsContext } from 'next'; export default function ProtectedPage() { return ( <ProtectedRoute> {/* 页面内容 */} </ProtectedRoute> ); } export const getServerSideProps = async (ctx: GetServerSidePropsContext) => { await verifyAuth(ctx); return { props: {} }; };
2. 配置Next.js Webpack忽略客户端的fs模块
在next.config.js中添加webpack配置,让客户端打包时跳过fs模块(因为firebase-admin依赖的fs仅在Node.js环境需要):
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config, { isServer }) => { if (!isServer) { // 客户端环境不引入fs模块 config.resolve.fallback = { ...config.resolve.fallback, fs: false, }; } return config; }, }; module.exports = nextConfig;
3. 确保Firebase Admin仅在服务器端初始化
检查你的firebaseAdmin初始化文件(../firebaseAdmin),确保它不会被客户端代码加载,示例写法:
import admin from 'firebase-admin'; // 避免重复初始化 if (!admin.apps.length) { admin.initializeApp({ // 你的Firebase Admin配置(如service account信息) }); } export const firebaseAdmin = admin;
完成以上步骤后,重新启动Next.js开发服务器,即可解决fs模块找不到的问题。
内容的提问来源于stack exchange,提问作者Space
相关产品推荐
相关产品推荐

