I’m currently exploring the new App router in NextJS 13.4 and encountered an issue while trying to execute an external API request. While I’m able to receive all the necessary data from Airtable, I experience a TypeError which interrupts my try-catch mechanism. I’m struggling to identify the cause of this error and how to resolve it. Here’s the specific error message I receive:
- error TypeError: Cannot read properties of undefined (reading 'headers')
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The initial request is being made from a client component located at /app/dashboard/page.js, which resembles the following:
'use client'
import React, { useEffect } from 'react';
const Dashboard = () => {
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('/api/jobs', {
method: 'GET',
headers: {
'id': '123'
}
});
const result = await response.json();
console.log("hello", result); // This log gets skipped due to the error caught below
} catch (error) {
console.log("An error occurred");
console.log(error);
}
};
fetchData();
}, []);
return (
<div>
Hello World
</div>
);
}
export default Dashboard;
Additionally, my handler is located at /app/api/jobs/route.js, structured as follows:
import { NextResponse } from 'next/server';
import { jobs } from "../../../utils/Airtable";
export async function GET(request) {
let headerValue = await request.headers.get('id'); // This retrieves the headers correctly
let recordsList = [];
try {
jobs.select({
view: 'Grid view',
fields: ['Project Leader'],
filterByFormula: `AND({Project Leader} = 'Jane Doe', AND({Created Day}, '6/1/23'))`
}).eachPage(function processPage(records, fetchNext) {
recordsList.push(...records);
try {
fetchNext();
} catch (err) {
console.log(err);
return;
}
}, function complete(err) {
if (err) {
return new NextResponse(JSON.stringify({message: 'Error'}));
}
console.log(recordsList); // This prints records successfully
return new NextResponse(JSON.stringify(recordsList));
});
} catch (err) {
return new NextResponse(JSON.stringify({message: 'Error'}), { status: 500 });
}
return new NextResponse(JSON.stringify(obj), { status: 200 });
}
Commenting out the Airtable API request eliminates the error. Also, when I move the Airtable API call into the client component, it executes perfectly. I suspect there’s a specific aspect of NextJS that I’m not grasping. I appreciate any insights you can provide.