I am building a project directly with Next.js 14 and have encountered an issue with API routes and Sanity integration. I have an API endpoint for Sanity with Groq queries, and everything works fine when I test the queries in Sanity Studio. However, I'm unable to get the expected data when I access the API endpoint using the new Next.js 14 API routes.
Here is my Folder structure:
- /app
- /api
- /getExperiences
- route.ts
When I navigate to http://localhost:3000/api/getExperiences, I expect to see the data from the query, but it's not working as expected. Both my Sanity server and local frontend server are running without issues.
Here is an example of Endpoint I created
import type { NextApiRequest, NextApiResponse } from "next";
import { groq } from "next-sanity";
import { sanityClient } from "../../../sanity";
import { Experience } from "@/typings";
const query = groq`*[_type == "experience"]{
...,
technologies[]->
}`;
type Data = {
experiences: Experience[];
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const experiences: Experience[] = await sanityClient.fetch(query);
res.status(200).json({ experiences });
}
I started my project directly with Next.js 14.
I tested my queries in Sanity Studio and it worked perfectly giving me the data I was asking for. I suspect there might be an issue with how I've structured the API routes in Next.js 14. Thanks for your precious help!