Next.js Discord

Discord Forum

getServerSession() doesnt seem to exist

Answered
The Fog from Human Resources posted this in #help-forum
Open in Discord
Avatar
Im trying to write API routes where i need to fetch the users session and apparently im supposed to use getServerSession() for it, but such function just doesnt exist
I 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
View full answer

31 Replies

Avatar
@The Fog from Human Resources Im trying to write API routes where i need to fetch the users session and apparently im supposed to use `getServerSession()` for it, but such function just doesnt exist I am using NextJS 15 and NextAuth 5 api/auth/[...nextAuth]/route.ts ts import { handlers } from "@/auth"; export const { GET, POST } = handlers; \@auth/index.ts 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
Avatar
when you import it directly like this:
import { getServerSession } from 'next-auth';

Which error do you get?

const session = await getServerSession();
Avatar
@B33fb0n3 when you import it directly like this: tsx import { getServerSession } from 'next-auth'; Which error do you get? tsx const session = await getServerSession();
Avatar
that seems to actually do something, now it wants the NextAuthConfig but i cant seem to export my authOptions from my auth handler
or the request
wait
nvm
Avatar
@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
Avatar
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, ...)
Avatar
im confused :thinker:
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 });
}
Avatar
lgtm
Avatar
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}
Avatar
can you log the session? Like console.log and then your session. Take a look what's inside there
Avatar
bet
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]
}
Avatar
im importing it like this
import getServerSession from "next-auth";
Avatar
@The Fog from Human Resources im importing it like this import getServerSession from "next-auth";
Avatar
try this one:
import { getServerSession } from 'next-auth';
Avatar
Module '"next-auth"' has no exported member 'getServerSession'. Did you mean to use 'import getServerSession from "next-auth"' instead?
Avatar
@The Fog from Human Resources `Module '"next-auth"' has no exported member 'getServerSession'. Did you mean to use 'import getServerSession from "next-auth"' instead?`
Avatar
I just wanted to check the docs again. As you said, you using nextAuth 5, but a v5 does not exists 🤔
Image
Avatar
uh
"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
Avatar
@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
Avatar
a my bad then. In next-auth beta you can get the session via:
const session = await auth()

if (!session?.user) return null
Answer
Avatar
that fixed it, tysm!
Avatar
happy to help
Avatar
Avatar
btw, cool username 😉
Avatar
thanks lmao
i feel stupid, auth is even a function i export in my auth handler file idk why i didnt check it :SCchaos: