Troubleshooting data transfer from Next.js backend to frontend

Help needed with Next.js data flow

I’m stuck with a Next.js app. My backend API gets data from the database just fine. But when I try to fetch it on the frontend, I keep getting an empty object. Here’s what I’ve got:

Backend (works OK):

import { dbConnect } from '@/utils/database';

export async function GET() {
  const orders = await dbConnect.orders.getAll();
  console.log('Orders:', JSON.stringify(orders));
  return Response.json(orders);
}

Frontend (not working):

async function fetchOrders() {
  const response = await fetch('/api/orders');
  console.log('Response:', JSON.stringify(response));
}

fetchOrders();

The backend log shows the data, but the frontend log always prints {}. What am I missing? How can I get the data to show up on the frontend?

hey there! sounds like ur missing a crucial step. after fetch, u gotta parse the response as JSON. try this:

async function fetchOrders() {
const response = await fetch(‘/api/orders’);
const data = await response.json();
console.log(‘Data:’, JSON.stringify(data));
}

this shud fix ur issue. lmk if it helps!

hey jasper! have u checked ur network tab in devtools? sometimes the data’s there but not visible in console.log. also, are u sure the API route is correct? maybe try ‘/api/orders/’ with a trailing slash? just brainstorming here. lemme know if any of this helps!

Based on your code, it appears you’re not awaiting the JSON parsing of the response. Here’s a modification that should resolve your issue:

async function fetchOrders() {
  try {
    const response = await fetch('/api/orders');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const orders = await response.json();
    console.log('Orders:', JSON.stringify(orders));
  } catch (error) {
    console.error('Fetching error:', error);
  }
}

This approach properly handles the asynchronous nature of the fetch request and JSON parsing. It also includes error handling to catch any potential issues during the process. Remember to call this function within a useEffect hook if you’re using it in a React component to avoid unnecessary re-renders.