so heres the updated version:
i created a new folder under app directory
app/api/twitch and in twitch folder created a route.ts
and this is my code for now
export async function GET(req: NextApiRequest, res: Response) {
const { user_id } = req.query;
console.log("User ID:", user_id);
const client_id = process.env.TWITCH_CLIENT_ID;
const client_secret = process.env.TWITCH_CLIENT_SECRET;
const appURL = `https://api.twitch.tv/helix/videos?user_id=${user_id}`;
if (!client_id || !client_secret) {
console.error("Twitch client ID or client secret not found");
throw new Error("Twitch client ID or client secret not found");
}
const tokenParams = new URLSearchParams({
client_id: client_id,
client_secret: client_secret,
grant_type: "client_credentials",
});
// Fetching access token
const tokenResponse = await fetch(`https://id.twitch.tv/oauth2/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: tokenParams,
});
if (!tokenResponse.ok) {
console.error("Failed to fetch access token:", tokenResponse.statusText);
throw new Error(
`Failed to fetch access token: ${tokenResponse.statusText}`
);
}
const tokenData = await tokenResponse.json();
const accessToken = tokenData.access_token;
// Fetching Twitch videos
const videoResponse = await fetch(appURL, {
headers: {
"Client-ID": client_id,
Authorization: `Bearer ${accessToken}`,
},
});
if (!videoResponse.ok) {
console.error("Failed to fetch videos:", videoResponse.statusText);
throw new Error(`Failed to fetch videos: ${videoResponse.statusText}`);
}
const result = await videoResponse.json();
console.log("Result:", result);
if (!result.data || result.data.length === 0) {
console.error("No videos found for the given user ID");
throw new Error("No videos found for the given user ID");
}
// res.status(200).json(result);
return Response.json(result);
}
and this is my page.tsx where i am trying to acces my own api
export interface TwitchVideoResponse {
data: TwitchVideo[];
}
export interface TwitchVideo {
id: string;
user_name: string;
title: string;
url: string;
thumbnail_url: string;
type?: string;
duration?: string;
}
const fetchTwitchVideos = async (user_id: string) => {
const videos = await fetch(
`http://localhost:3000/api/twitch?user_id=${user_id}`
);
console.log("Twitch Videos:", videos);
const data: TwitchVideoResponse = await videos.json();
console.log("Twitch Videos:", data);
return data;
};
const TwitchPage = async () => {
const videos: TwitchVideoResponse = await fetchTwitchVideos("1234567890");
return (
<div>
<h1>Twitch Videos</h1>
{videos.data.map((video: TwitchVideo) => (
<h1 key={video.id}>{video.title}</h1>
))}
</div>
);
};
export default TwitchPage;
THE BODY MESSAGE OF RESPONSE
_Response {
type: 'basic',
url: 'http://localhost:3000/api/twitch?user_id=1234567890',
redirected: false,
status: 500,
ok: false,
statusText: 'Internal Server Error',
headers: _Headers {
Symbol(headers list): _HeadersList {
cookies: null,
Symbol(headers map): Map {
vary: {
name: 'vary',
value: 'RSC, Next-Router-State-Tree, Next-Router-Prefetch'
},
date: { name: 'Date', value: 'Wed, 05 Jun 2024 17:19:04 GMT' },
connection: { name: 'Connection', value: 'keep-alive' },
keep-alive: { name: 'Keep-Alive', value: 'timeout=5' },
transfer-encoding: { name: 'Transfer-Encoding', value: 'chunked' }
},
Symbol(headers map sorted): null
},
Symbol(guard): 'immutable',
Symbol(realm): null
},
body: ReadableStream {
locked: false,
Symbol(kType): 'ReadableStream',
Symbol(kState): {
disturbed: false,
state: 'readable',
storedError: undefined,
stream: undefined,
transfer: { writable: undefined, port: undefined, promise: undefined },
controller: ReadableStreamDefaultController {
desiredSize: 1,
Symbol(kType): 'ReadableStreamDefaultController',
Symbol(kState): {
closeRequested: false,
highWaterMark: 1,
pullAgain: false,
pulling: false,
queue: [],
queueTotalSize: 0,
started: true,
stream: TeeReadableStream {
locked: false,
Symbol(kType): 'ReadableStream',
Symbol(kState): {...},
Symbol(nodejs.webstream.isClosedPromise): {
promise: Promise {
Symbol(async_id_symbol): 179243,
Symbol(trigger_async_id_symbol): 178103,
Symbol(kResourceStore): {
headers: bound a {
headers: {...},
Symbol(headers list): _HeadersList {...},
Symbol(guard): 'none'
},
cookies: bound f { _parsed: Map {...}, _headers: a {...} },
mutableCookies: bound p {
_parsed: Map {...},
_headers: _Headers {...}
},
draftMode: tU {
isEnabled: false,
_previewModeId: 'f7a857a23c02b90a14f8664289afa3df',
_mutableCookies: bound p {...}
},
reactLoadableManifest: {},
assetPrefix: ''
}
}
}
}
}
}
},
… and the error continues
This error comes from
const videos = await fetch(
`http://localhost:3000/api/twitch?user_id=${user_id}`
);
console.log("Twitch Videos:", videos); 'here'
Can you tell me if my function on GET is correct or not? if not what am i doing wrong