Hello, I'm currently learning Next.js 13 and I'm trying to fetch data from a PocketBase database to display in a table. I've created an API route that connects to the database and retrieves the data. However, I'm having trouble fetching this data in a server component.
Here's the structure of my project:
app/
api/
ingresos/
route.ts
components/
tablaIngresosCliente.tsx
ingresos/
page.tsx
...
In route.ts, I connect to the PocketBase database and fetch the data:
// app/api/ingresos/route.ts
import { NextResponse } from 'next/server';
import PocketBase from 'pocketbase';
export async function GET(request: Request) {
const pb = new PocketBase('http://127.0.0.1:8090');
try {
const records = await pb.collection('ingresos').getFullList({
sort: '-created',
});
return NextResponse.json(records);
} catch (error) {
console.error(error)
return new Response('Could not fetch', { status: 500 })
}
}
In tablaIngresosCliente.tsx, I'm trying to fetch the data from the API route:
export default async function TablaIngresos() {
const res = await fetch('/api/ingresos');
const ingresos = await res.json();
// Render table with ingresos data
}
However, I'm encountering an error when trying to fetch the data from the API route in the server component. The error message is "Failed to parse URL from /api/ingresos".
I understand that server components run on the server and don't have access to the same base URL as client-side code. But I'm not sure how to correctly fetch data from a local API route in a server component.
Moreover, I'm wondering if this is the correct approach for fetching data in Next.js 13. Is it recommended to fetch data from an API route in a server component, or is there a better way to fetch and display data in Next.js 13?
Any guidance would be greatly appreciated. Thank you!