samuel potter
samuel potter

Reputation: 209

Value of this must be of type EventTarget

I'm on the latest version of nextjs with the App Router. I'm trying to get fetch the data from my next api on the /api endpoint but it returns an error 500.

Error [ERR_INTERNAL_ASSERTION]: TypeError [ERR_INVALID_THIS]: Value of "this" must be of type EventTarget

This is the content of the next api file app/api/route.ts:

import { NextResponse } from "next/server";
import { NextApiRequest, NextApiResponse } from "next";

export const POST = async (req: NextApiRequest, res: NextApiResponse) => {
  console.log(req);

  return NextResponse.json({ data: "accessToken" });
};

and this is how I'm trying to call it in the server side:

"use client";

import { useSearchParams } from "next/navigation";

export default function Home() {
  const authorizeTwitchApp = `${process.env.twitchApiUrl}/oauth2/authorize?response_type=code&client_id=${process.env.twitchClientId}&redirect_uri=http://localhost:3000&scope=channel%3Amanage%3Apolls+channel%3Aread%3Apolls+openid`;

  const queryParam = useSearchParams().get("code");

  const getAccessToken = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();

    const response = await fetch("http://localhost:3000/api", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ code: queryParam }),
    });

    const data = await response.json();

    console.log(data);
  };

  return (
    <div>
      <a href={authorizeTwitchApp}>click me !!</a>
      <button onClick={(e) => getAccessToken(e)}>send code to api !!</button>
    </div>
  );
}

Upvotes: 1

Views: 390

Answers (1)

LiiChar
LiiChar

Reputation: 1

I had the same mistake. As I understood from the documentation https://nextjs.org/docs/app/api-reference/file-conventions/route. Request is received in the form of a promise, after which you need to convert it to an object using the method .json()

Upvotes: 0

Related Questions