Frontend component receives empty object when fetching data from Next.js API route

I’m building a Next.js app and running into an issue where my frontend component gets an empty object when calling my API route, even though the API is returning data correctly.

Backend API Route

My API route at pages/api/orders/index.js fetches data from database:

import { db } from "@/utils/database";

export default async function handler(req, res) {
    if (req.method === 'GET') {
        const ordersList = await db.orders.findAll();
        
        console.log("Database orders:", JSON.stringify(ordersList));
        
        return res.status(200).json(ordersList);
    }
}

The backend logs show data is retrieved successfully:

Database orders: [{"order_id":10,"created_at":"2024-09-12T08:15:30.123Z","customer_table":5,"item":"Coffee","completed":true}]

Frontend Component Issue

But when I call this API from my component:

"use client";
import { useState, useEffect } from 'react';

const OrderManager = () => {
    const [orders, setOrders] = useState([]);
    
    const fetchOrders = async () => {
        const response = await fetch('/api/orders');
        console.log("API response:", JSON.stringify(response));
    };
    
    useEffect(() => {
        fetchOrders();
    }, []);
    
    return (
        <div>
            {/* Component JSX */}
        </div>
    );
};

export default OrderManager;

The console shows an empty object instead of the actual data. What am I missing here? The API works fine but the frontend isn’t getting the right data.

Hmm, interesting. are you handling errors in your fetch? the api might be throwing errors you’re not seing without proper error handling. check your network tab in dev tools - does it show the correct response there?

classic mistake lol. you’re logging the raw fetch response instead of the actual data. you need to await response.json() first, then log that. also don’t forget to actually set your orders state or nothing will show up.

You’re logging the response object instead of the actual data. The fetch API returns a Response object that you need to parse first. Call .json() on the response to get the content:

const fetchOrders = async () => {
const response = await fetch(‘/api/orders’);
const data = await response.json();
console.log(“API response:”, JSON.stringify(data));
setOrders(data);
};

I hit this same issue when I started with Next.js APIs. The Response object has request metadata, not your actual payload. Add the .json() step and you’ll see your orders data properly in your component state.