reactjs - The session from next-auth is always null - Stack Overflow

admin2025-05-02  1

I have a Next.jsAPI route at /api/getPost/[id]/route.ts. When I try to fetch the session using await auth() in this route, it always returns null. This issue does not occur in other API routes, SSR pages, or CSR pages, where the session is retrieved successfully. However, the session always returns null in /api/getPost/[id]/route.ts. Why is this happening? I am using the following version of the framework/library.

"next": "14.2.16", (app router)

"next-auth": "^5.0.0-beta.25",

// /api/getPost/[id]/route.ts

import { db } from "@/app/lib/db";
import { PostTypes } from "@/app/lib/definitions";
import { ResultSetHeader } from "mysql2";
import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  const post_id = params.id;
  if (!post_id) {
    return NextResponse.json({ error: "Post ID is required" }, { status: 400 });
  }
  const session = await auth();
  console.log("session = ",session); // session is always null
 // ... some codes...
}
// API route where the session works"
// /api/getComments/route.ts
export async function GET(
  request: Request
): Promise<NextResponse<InfiniteQueryResponse<CommentsTypes[]>>> {
  const session = await auth();
  console.log("session = ",session); // The session returns the correct value.
  // ...codes ...
// auth.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { getUser } from "./app/lib/data";

export const { handlers, auth } = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  callbacks: {
    async signIn({ profile, user }) {
      const [isExistingUser] = await getUser(profile?.sub as string);
      console.log("isExistingUser = ", isExistingUser);
      if (!isExistingUser) {
        user.isNewUser = true;
      } else {
        user.nickname = isExistingUser.nickname;
      }
      return true;
    },
    async jwt({ token, account, profile, user, trigger, session }) {
      if (account && profile) {
        token.sub = profile.sub as string;
        token.name = profile.name;
        token.email = profile.email;
      }
      if (user) {
        token.isNewUser = user.isNewUser;
        token.nickname = user.nickname;
      }

      if (trigger === "update" && session !== null) {
        return { ...session.user };
      }

      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = (token.sub || token.id) as string;
        session.user.isNewUser = token.isNewUser as boolean;
        session.user.nickname = token.nickname as string;
      }
      return session;
    },
  },
  pages: {
    signIn: "/login",
    newUser: "/sign-up",
  },
});

// ./middleware.ts
import { NextResponse } from "next/server";
import { auth } from "./auth";

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  const PostPage = req.nextUrl.pathname.startsWith("/post");
  const MyPage = req.nextUrl.pathname.startsWith("/mypage");

  if ((PostPage || MyPage) && !isLoggedIn) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};

I have a Next.jsAPI route at /api/getPost/[id]/route.ts. When I try to fetch the session using await auth() in this route, it always returns null. This issue does not occur in other API routes, SSR pages, or CSR pages, where the session is retrieved successfully. However, the session always returns null in /api/getPost/[id]/route.ts. Why is this happening? I am using the following version of the framework/library.

"next": "14.2.16", (app router)

"next-auth": "^5.0.0-beta.25",

// /api/getPost/[id]/route.ts

import { db } from "@/app/lib/db";
import { PostTypes } from "@/app/lib/definitions";
import { ResultSetHeader } from "mysql2";
import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  const post_id = params.id;
  if (!post_id) {
    return NextResponse.json({ error: "Post ID is required" }, { status: 400 });
  }
  const session = await auth();
  console.log("session = ",session); // session is always null
 // ... some codes...
}
// API route where the session works"
// /api/getComments/route.ts
export async function GET(
  request: Request
): Promise<NextResponse<InfiniteQueryResponse<CommentsTypes[]>>> {
  const session = await auth();
  console.log("session = ",session); // The session returns the correct value.
  // ...codes ...
// auth.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { getUser } from "./app/lib/data";

export const { handlers, auth } = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  callbacks: {
    async signIn({ profile, user }) {
      const [isExistingUser] = await getUser(profile?.sub as string);
      console.log("isExistingUser = ", isExistingUser);
      if (!isExistingUser) {
        user.isNewUser = true;
      } else {
        user.nickname = isExistingUser.nickname;
      }
      return true;
    },
    async jwt({ token, account, profile, user, trigger, session }) {
      if (account && profile) {
        token.sub = profile.sub as string;
        token.name = profile.name;
        token.email = profile.email;
      }
      if (user) {
        token.isNewUser = user.isNewUser;
        token.nickname = user.nickname;
      }

      if (trigger === "update" && session !== null) {
        return { ...session.user };
      }

      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = (token.sub || token.id) as string;
        session.user.isNewUser = token.isNewUser as boolean;
        session.user.nickname = token.nickname as string;
      }
      return session;
    },
  },
  pages: {
    signIn: "/login",
    newUser: "/sign-up",
  },
});

// ./middleware.ts
import { NextResponse } from "next/server";
import { auth } from "./auth";

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  const PostPage = req.nextUrl.pathname.startsWith("/post");
  const MyPage = req.nextUrl.pathname.startsWith("/mypage");

  if ((PostPage || MyPage) && !isLoggedIn) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};
Share Improve this question edited Jan 2 at 14:54 이준희 asked Jan 2 at 12:32 이준희이준희 134 bronze badges 2
  • The problem is with your routes. Works on /api/getComments/route.ts but doesn't on /api/getPost/[id]/route.ts. Make sure of your configurations – Sarkis Commented Jan 2 at 14:07
  • @Sarkis I'm sorry, but I didn't understand what you meant. By 'configurations,' are you referring to the middleware for next-auth? I have included middleware.tsin the body. Or are you suggesting that there is an issue with the dynamic routing in the /app/api/getPost/[id]/route.ts file? – 이준희 Commented Jan 2 at 14:56
Add a comment  | 

1 Answer 1

Reset to default 0

Wrap it up with auth method from auth.ts file

import { auth } from "auth"

export const GET = auth(async function GET(request: Request) {
    // @ts-ignore
    const { auth } = request
    // @ts-ignore
    console.log("session (API routes)", auth)
})

Read more on https://authjs.dev/getting-started/session-management/protecting

转载请注明原文地址:http://www.anycun.com/QandA/1746120198a91947.html