error TypeError: Cannot read properties of undefined (reading ‘headers’) with nextjs [duplicate]

I have an app router setup with the code below. When calling the endpoint, i get Internal Server Error: 500, with the error log on server error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:266:61)

import { NextRequest, NextResponse } from 'next/server';

// Import and initialize your gRPC client here
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');

var PROTO_PATH = __dirname + '/../myproto.proto';

try {
  var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  });
} catch (error) {
  console.error('Error loading proto file:', error);
}

var qProto = grpc.loadPackageDefinition(packageDefinition).myproto;

var client = new qProto.QEngine('localhost:6767', grpc.credentials.createInsecure())

export async function POST(req: Request, res: Response) {
  try {
    const body = await req.json()
    var reqq = qProto.QueryRequest;

    reqq.query_string = body.queryString
    reqq.debug = body.debug;

    // Make the gRPC query call using your gRPC client
    client.Query(reqq, function(err: Error, grpcResponse: any) {
      // console.log('gRPC Response:', JSON.stringify(grpcResponse, null, 2));
      if (err) {
        console.error('Error calling Query:', err);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
      } else {
        // Set the status code and send the response directly using res.json
        return NextResponse.json({ data: grpcResponse }, { status: 200 })
      }
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}

on investigating my breakpoints, i see that as soon as client.Query() is called, a 500 error is returned (testing with postman), without waiting to reach either of the return statements. I am able to see the grpcResponse being populated correctly. Not sure what’s causing it to return early.

using nextjs and testing code locally on vscode.