Next.js Discord

Discord Forum

Trouble sending a form to the backend using the AI SDK libraries

Unanswered
Large garden bumble bee posted this in #help-forum
Open in Discord
Avatar
Large garden bumble beeOP
I have a form which is fairly simple and looks as follows:
interface ChatFormProps extends ComponentProps<'form'> {
  input?: string;
  handleInputChange?: ChangeEventHandler<HTMLTextAreaElement>;
}

function ChatForm({
  input,
  handleInputChange,
  ...props
}: ComponentPropsWithRef<'form'>) {
  const promptId = useId();
  return (
    <form {...props}>
      <div role="group">
        <label htmlFor={promptId}>Send Message</label>
        <textarea id="prompt" name="prompt" value={input} onChange={handleInputChange} />
      </div>
      <button type="submit">Send</button>
    </form>
  );
}

I use this in one place like so, and it works fine:
function CreateChat() {
  return (
    <section className="flex flex-col">
      <EmptyChatScreen />
      <ChatForm method="POST" action="/api/v2/chat" />
    </section>
  );
}

However, I am trying to use this with the AI useChat and it's not working
export default function Chat({ chatId }) {
  const csrfToken = useCsrfToken();
  const { messages, handleSubmit, input, handleInputChange, isLoading } = useChat({
    api: `/api/v2/chat/${chatId}/generate`,
    headers: {
      'X-CSRF-Token': csrfToken!,
    },
  });
  return (
    <section className="flex flex-col">
      <ChatLog id={chatId} messages={messages} />
      <ChatForm
        onSubmit={handleSubmit}
        aria-busy={isLoading}
        input={input}
        handleInputChange={handleInputChange}
      />
    </section>
  );
}

Here's the problem: whenever I send to the backend, I can get one of multiple errors, the first being:
TypeError: Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".

I've tried to set the 'Content-Type' in the header to application/x-www-form-urlencoded, but when I inspect the form data, I don't have a prompt available
When I set it to multipart/form-data, it gives me the error Failed to parse body as FormData.

export async function POST(request: NextRequest) {
  const formData = await request.formData();
  console.log(formData.get('prompt')!); // always null
  return NextResponse.json();
}

I've also tried passing through the input and handleInputChange to the ChatForm using the handlers from useChat, which also did not work


Strangely, I should add, manually passing an action that makes a fetch request from the client does work

Any ideas?

0 Replies