next.jssession-cookiesnext-auth

Error "Session cookie exceeds allowed 4096 bytes." in next-auth using Next.js 14 typescript


Previously I used next.js version 13.x.x then upgraded to next.js version 14.x.x When using next.js 13, authentication with next-auth runs smoothly, but after upgrading to next.js 14 an error like this occurs in the terminal console message: 'Session cookie exceeds allowed 4096 bytes.'

this is my complete code in authoptions

import { AuthOptions } from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import prisma from "./prisma";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";

export const authOptions: AuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        CredentialsProvider({
            credentials: {
                email: { label: 'email', type: 'text' },
                password: { label: 'password', type: 'password' },
            },

            authorize: async (credential) => {
                if (!credential?.email || !credential?.password) {
                    throw new Error("Invalid email or password");
                }

                const user = await prisma.user.findUnique({
                    where: { email: credential.email },
                    include: {
                        histories: true,
                        resto: true,
                    }
                });

                if (!user || !user?.password) {
                    throw new Error("Email does not match any user...");
                }

                const isCorrect = await bcrypt.compare(credential.password, user.password)
                if (!isCorrect) {
                    throw new Error("Password salah euy")
                }

                return {
                    ...user,
                    id: user.id.toString(),
                    name: user.name,
                    role: user.role,
                };
            },
        })
    ],
    callbacks: {
        jwt: async ({ token, user, session, trigger }) => {
            if (trigger === 'update') {
                return {
                    ...token,
                    ...session.user
                }
            }

            if (user) {
                const userRelation = await prisma.user.findUnique({
                    where: { id: Number(user.id) },
                    include: {
                        histories: true,
                        resto: true,
                    }
                });

                if (!userRelation) {
                    throw new Error("User not found");
                }

                return {
                    ...token,
                    // id: user.id,
                    ...userRelation
                };
            }

            if (token.name !== null && token.name !== undefined) {
                await prisma.user.update({
                    where: { id: Number(token.id) },
                    data: { name: token.name }
                });
            }

            return token;
        },
        session: async ({ session, token, user }) => {
            const newSession = {
                ...session,
                user: {
                    ...session.user,
                    id: token.id,
                    name: token.name,
                    role: token.role,
                }
            }

            return newSession;
        },
    },
    pages: {
        signIn: '/',
        error: '/',
    },
    debug: true,
    session: { strategy: "jwt" },
    secret: "rahasia",
}

then call the authoptions in file route.ts

// route.ts
import { authOptions } from '@/lib/auth';
import NextAuth from 'next-auth';

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }

and this is my file next-auth.d.ts

// next-auth.d.ts
import NextAuth from "next-auth";

declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      name: string;
      email: string;
      role: string;
      [key: string]: string;
    };
  }
}

How may I solve the issue? or i should be downgrade to next.js version 13.x.x. again


Solution

  • I changed the body of the jwt callback to be more concise, and it worked

    jwt: async ({ token, user, session, trigger }) => {
            if (trigger === 'update') {
                return {
                    ...token,
                    ...session.user
                }
            }
    
            if (user) {
                if (!user) return token
    
                return {
                    ...token,
                    id: user.id,
                    role: user.role,
                }
            }
    
            if (token.name !== null && token.name !== undefined) {
                await prisma.user.update({
                    where: { id: Number(token.id) },
                    data: { name: token.name }
                });
            }
    
            return token;
        },