You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 13.5升级后生产环境登录报错:SessionEntity无元数据

解决NextJS 13.5升级后TypeORM-Adapter生产环境SessionEntity元数据丢失问题

针对你遇到的生产环境登录报错(No metadata for "SessionEntity" was found),以下是可行的解决方案:

  • 显式注册TypeORM实体
    生产构建时NextJS的树摇优化可能移除未被直接引用的实体,不要依赖路径扫描的方式注册实体。直接在DataSource配置里导入并声明所有实体:

    import { SessionEntity } from "./entities/SessionEntity";
    import { UserEntity } from "./entities/UserEntity";
    // 导入其他用到的实体
    
    export const AppDataSource = new DataSource({
      type: "postgres",
      host: process.env.DB_HOST,
      // 其他数据库配置
      entities: [SessionEntity, UserEntity, /* 其他实体 */], // 显式列出所有实体
    });
    
  • 调整NextJS生产构建的webpack配置
    NextJS 13.5的模块打包优化可能影响TypeORM的元数据生成。在next.config.js中添加配置,避免TypeORM被过度优化:

    const nextConfig = {
      webpack: (config) => {
        // 把typeorm排除在webpack的模块打包外,防止元数据丢失
        config.externals.push("typeorm");
        return config;
      },
    };
    
    module.exports = nextConfig;
    

    或者尝试启用针对性的包优化:

    const nextConfig = {
      experimental: {
        optimizePackageImports: ["typeorm", "@next-auth/typeorm-adapter"],
      },
    };
    
    module.exports = nextConfig;
    
  • 检查SessionEntity的装饰器配置
    确认SessionEntity的@Entity装饰器配置正确,类名与实体映射一致:

    import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
    
    @Entity("session") // 确保表名与数据库中一致,类名SessionEntity对应
    export class SessionEntity {
      @PrimaryGeneratedColumn("uuid")
      id: string;
    
      @Column("varchar")
      sessionToken: string;
    
      @Column("varchar")
      userId: string;
    
      @Column("timestamp")
      expires: Date;
    
      // 其他关联字段...
    }
    
  • 在NextAuth中显式指定适配器实体
    确保next-auth的TypeORM适配器使用你自定义的实体,而不是默认实现:

    import NextAuth from "next-auth";
    import { TypeORMSessionAdapter } from "@next-auth/typeorm-adapter";
    import { AppDataSource } from "../data-source";
    import { SessionEntity } from "../entities/SessionEntity";
    import { UserEntity } from "../entities/UserEntity";
    
    export const { auth, handlers, signIn, signOut } = NextAuth({
      adapter: TypeORMSessionAdapter(AppDataSource, {
        session: SessionEntity,
        user: UserEntity,
        // 配置其他用到的实体(account, verificationToken等)
      }),
      // 其他NextAuth配置...
    });
    
  • 清理构建缓存后重新打包
    旧的构建缓存可能导致实体元数据未更新,执行以下命令清理后重新构建生产环境:

    rm -rf .next/ node_modules/.cache/
    npm run build
    

内容的提问来源于stack exchange,提问作者Guy Korland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:03:32