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$).*)"],
};
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
/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