I keep getting this issue when trying to call the Claude API in my code.

However, in my Anthropic console it says that the API is working and it's logging each time I press the button to call it. I am using Next js typescript and using the Anthropic SDK, I followed the docs on how to call the API but still no luck.
I have multiple variations of the route.ts and frontend code, but cannot fix it; my paths structures are correct. I have also tried using axios to just call it from the frontend component, just to see if I could get it to work, but it still gave me the same error.
This is my code that is calling it but still giving me that error.
Here is my page.tsx where it simply calls the API with a button press: Here is the formatted code with 4-space indentation and proper formatting for Stack Overflow:
"use client";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
export default function ClaudeInteraction() {
const [responseText, setResponseText] = useState<string>("");
const handleSubmit = async () => {
try {
const response = await fetch("/api/claude-api", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: "Hello there" }),
});
if (!response.ok) {
throw new Error("Failed to get response from Claude API");
}
const data = await response.json();
setResponseText(data.text);
} catch (error) {
console.error("Error getting response from Claude:", error);
setResponseText("Error: Unable to get response from Claude.");
}
};
return (
<div className="text-white">
<Button onClick={handleSubmit}>Send Request to Claude</Button>
{responseText && <div>Response: {responseText}</div>}
</div>
);
}
import { NextApiRequest, NextApiResponse } from 'next';
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
export async function POST(req: NextApiRequest, res: NextApiResponse) {
const { message } = req.body;
try {
const result = await client.messages.create({
messages: [
{
role: 'user',
content: "Hello there",
},
],
model: 'claude-3-haiku-20240307',
max_tokens: 100,
});
res.status(200).json({ text: result.content });
} catch (error) {
console.error('Error fetching response:', error);
res.status(500).json({ error: 'Error fetching response' });
}
}
console.log(response)before the error is thrown?