sessionnext.jsnext-auth

Next JS 14 nextAuth getServerSession not working


import { NextRequest, NextResponse } from "next/server";
import supabase from "@/app/backend/db/supabase";
import { getServerSession } from "next-auth/next";
import authOptions from "@/app/backend/lib/authentication/authOptions";

export async function GET(
  req: NextRequest,
  { params }: { params: { slug: string[] } }
) {
  const session = await getServerSession(authOptions);
  console.log("aaaaa", session);
  if (session?.user) {
    try {
      const { slug } = params;
      console.log(slug);
      let { data, error } = await supabase
        .from(slug[0])
        .select("*")
        .eq(slug[1], slug[2]);

      if (error) {
        console.log(error);
        return NextResponse.json({ error: error.message }, { status: 500 });
      }

      return NextResponse.json({ success: true, data }, { status: 200 });
    } catch (error) {
      console.log(error);
      return NextResponse.json(
        { error: "Internal Server Error" },
        { status: 500 }
      );
    }
  } else {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
}

Im using Next JS 14 and nextAuth for authentication using credentials. Im trying to get the session on my API route but the session keep returning as null. When testing at the same time on client side i can access the session. Can anyone help me?


Solution

  • maybe you can try : Use getToken instead of getServerSession: Try using getToken to manually retrieve the token from the request, as getServerSession may return null in API routes without a valid token.

    Configure NEXTAUTH_SECRET: Ensure that NEXTAUTH_SECRET is correctly set in environment variables, as it’s required for token verification in API routes.

    Set Session Strategy to jwt: In your next-auth options, make sure session: { strategy: "jwt" } is set, especially for credential-based authentication.

    If none of this help, u better get some pen and paper to go through all the steps one by one.