Search code examples
javascriptnode.jsnext.jsprismanext-auth

TypeError: res.getHeader is not a function in NextJS API


I am trying to create a web application with NextJS 13 with TypeScript, Next Auth v4, Prisma (with a SQLite database for development) and OpenAI.

The console displays an error whenever I access to the API endpoint with the following message:

error - TypeError: res.getHeader is not a function

at setCookie (webpack-internal:///(sc_server)/./node_modules/next-auth/next/utils.js:11:49)

I have detected that the code fails whenever it tries to assign the session variable with getServerSession() at this line:

export async function GET(
    req: NextApiRequest, 
    res: NextApiResponse
) {
    const session = await getServerSession(req, res, authOptions) // <-- here it fails
    const sessionErrors = checkSessionErrors(session, req.url);
    if (sessionErrors) return sessionErrors;

    // rest of the code
}

I have been researching over the internet and I found some issues related to a Webpack middleware. But I am not using any middleware.

I have tried also replacing the code to look like this:

export async function GET(req: NextRequest) {
    const session = await getServerSession() // not sure how to fill this now
    const sessionErrors = checkSessionErrors(session, req.url);
    if (sessionErrors) return sessionErrors;

    // rest of the code
    // return stuff with NextResponse.json()
}

Not sure how to proceed now, any suggested actions on this?


Solution

  • getServerSession expects NextApiRequest and NextApiResponse arguments. I solved this by adding the getHeader and setHeader functions to NextResponse:

    export async function POST(req: NextRequest, res: NextResponse) {
      const session = await getServerSession(
        req as unknown as NextApiRequest,
        {
          ...res,
          getHeader: (name: string) => res.headers?.get(name),
          setHeader: (name: string, value: string) => res.headers?.set(name, value),
        } as unknown as NextApiResponse,
        authOptions
      );
    }