im-mahadi
im-mahadi

Reputation: 11

NextJs 13(app dir) fetch data from build in api

I am using Nextjs 13 with /src and /app directory. Below I am trying to fetch data from nextjs api:

//src/app/page.tsx
const getProducts = async () => {
  try {
    const res = await fetch('/api/products');
    const data = await res.json();
    return data;
  } catch (err) {
    console.log(err);
  }
}

export default async function Home() {
....
}
//src/pages/api/products
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Product[]>
) {
  res.status(200).json(products)
}

this doesn't work and instead show Failed to parse URL from /api/products and TypeError [ERR_INVALID_URL]: Invalid URL.

Note: When I fetch the same data using localhost:3000 with url that does work perfectly fine.

I even tried using `/pages/api/products' that doesn't work either.

Upvotes: 1

Views: 1192

Answers (1)

Naeem Ahmed
Naeem Ahmed

Reputation: 276

please create index.js inside /api/products/index.js and then build your endpoint and call that from Component as you did above

e.g

 export default function handler(req, res) {
        res.status(200).json([{id:1, title:'T-Shirt'},{id:2,title:'Shoes'}]);
}

Upvotes: 0

Related Questions