getServerSession() doesnt seem to exist
Answered
The Fog from Human Resources posted this in #help-forum
Im trying to write API routes where i need to fetch the users session and apparently im supposed to use
I am using NextJS 15 and NextAuth 5
api/auth/[...nextAuth]/route.ts
@auth/index.ts
I dont know what im doing wrong but the function im looking for just doesnt seem to exist
getServerSession()
for it, but such function just doesnt existI am using NextJS 15 and NextAuth 5
api/auth/[...nextAuth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
@auth/index.ts
/* eslint-disable @typescript-eslint/no-explicit-any */
import NextAuth, { NextAuthConfig, User } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { validateUserCredentialsAsync } from "./userAuthHelper";
const BASE_PATH = "/login";
const authOptions: NextAuthConfig = {
providers: [
Credentials({
name: "Credentials",
credentials: {...},
async authorize(credentials): Promise<User | null> {...},
}),
],
secret: process.env.NEXTAUTH_JWT_SECRET,
pages: {
signIn: BASE_PATH,
},
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, user }: { token: any; user: any }) {
if (user) {
token.role = user.role;
token.id = user.id;
}
return token;
},
async session({ session, token }: { token: any; session: any }) {
session.user.role = token.role;
session.user.id = token.id;
return session;
},
},
};
export const { handlers, auth, signIn, signOut } = NextAuth(authOptions);
I dont know what im doing wrong but the function im looking for just doesnt seem to exist
Answered by B33fb0n3
a my bad then. In next-auth beta you can get the session via:
const session = await auth()
if (!session?.user) return null
31 Replies
@B33fb0n3 when you import it directly like this:
tsx
import { getServerSession } from 'next-auth';
Which error do you get?
tsx
const session = await getServerSession();
that seems to actually do something, now it wants the NextAuthConfig but i cant seem to export my
authOptions
from my auth handleror the request
wait
nvm
@The Fog from Human Resources that seems to actually do something, now it wants the NextAuthConfig but i cant seem to export my `authOptions` from my auth handler
yes, add your authConfig to the function. The config should be just an object laying somewhere. For example inside your
auth.ts
or wherever. Then you can reuse it everywhere (in your route handlers, pages, ...)im confused
this is my code
like my route
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
const response: ErrorResponse = {
status: 1,
message: "You must be logged in to perform this action",
};
return NextResponse.json(response, { status: 401 });
}
const targetUser = await prisma.users.findFirst({
where: { id: session?.user?.id },
});
if (!targetUser) {
const response: ErrorResponse = {
status: 2,
message: "The user you are trying to target does not exist",
};
return NextResponse.json(response, { status: 404 });
}
const successResponse: SuccessResponse = {
status: 0,
username: targetUser.username,
createdAt: targetUser.createdAt,
modifiedAt: targetUser.modifiedAt,
role: targetUser.role,
};
return NextResponse.json(successResponse, { status: 200 });
}
lgtm
so when i use Curl in my command line i should get back the first response which is that i need to be logged in
but i get this:
{"status":0,"username":"admin","createdAt":"2025-01-05T03:04:50.112Z","modifiedAt":"2025-01-05T03:04:50.112Z","role":2}
can you log the session? Like
console.log
and then your session. Take a look what's inside therethe result of
console.log(session)
is{
handlers: { GET: [Function: httpHandler], POST: [Function: httpHandler] },
auth: [Function (anonymous)],
signIn: [Function: signIn],
signOut: [Function: signOut],
unstable_update: [Function: unstable_update]
}
@The Fog from Human Resources the result of `console.log(session)` is
{
handlers: { GET: [Function: httpHandler], POST: [Function: httpHandler] },
auth: [Function (anonymous)],
signIn: [Function: signIn],
signOut: [Function: signOut],
unstable_update: [Function: unstable_update]
}
that does not look right. Are you sure you importing the function from the correct location?
im importing it like this
import getServerSession from "next-auth";
@The Fog from Human Resources im importing it like this
import getServerSession from "next-auth";
try this one:
import { getServerSession } from 'next-auth';
Module '"next-auth"' has no exported member 'getServerSession'. Did you mean to use 'import getServerSession from "next-auth"' instead?
@The Fog from Human Resources `Module '"next-auth"' has no exported member 'getServerSession'. Did you mean to use 'import getServerSession from "next-auth"' instead?`
I just wanted to check the docs again. As you said, you using nextAuth 5, but a v5 does not exists 🤔
"next-auth": "5.0.0-beta.25",
i dont fully remember why i chose this but on a previous project this was the version that worked cause an older version would throw an error somewhere
@The Fog from Human Resources i dont fully remember why i chose this but on a previous project this was the version that worked cause an older version would throw an error somewhere
a my bad then. In next-auth beta you can get the session via:
const session = await auth()
if (!session?.user) return null
Answer
that fixed it, tysm!
happy to help
btw, cool username 😉
thanks lmao
i feel stupid,
auth
is even a function i export in my auth handler file idk why i didnt check it