Track Usage with Clerk
Overview
Step 1: Configuring your ARES API route
import { auth, clerkClient } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
export const runtime = "edge";
// GET Method: Access user's information on ARES's server.
export async function GET() {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ message: "User not signed in" });
}
// Get the OAuth access token for the user. Necessary to access ARES's API endpoints.
const provider = "custom_ares";
const client = await clerkClient();
const clerkResponse = await client.users.getUserOauthAccessToken(
userId,
provider
);
const accessToken = clerkResponse.data[0]?.token || "";
// Error Handling
if (!accessToken) {
return NextResponse.json(
{ message: "Access token not found" },
{ status: 401 }
);
}
// Get user's info from ARES API Endpoint. More information about this endpoint in the API Endpoints section.
const ARESUrl = "https://oauth.joinares.com/v1/user";
const ARESResponse = await fetch(ARESUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
// Error handling
if (!ARESResponse.ok) {
console.log(ARESResponse);
return NextResponse.json(
{ error: `ARES API error: ${ARESResponse.status}` },
{ status: ARESResponse.status }
);
}
// Handle the response from the ARES API
const ARESUserData = await ARESResponse.json();
return NextResponse.json(ARESUserData);
}
export async function POST(req: Request) {
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ message: "User not found" }, { status: 401 });
}
// Get request body
const { client_id, usage, credits } = await req.json();
// Validate required fields
if (!client_id || !usage || credits === undefined) {
return NextResponse.json(
{ message: "Missing required fields" },
{ status: 400 }
);
}
// Get the OAuth access token for the user. Necessary to access ARES's API endpoints.
const provider = "custom_ares";
const client = await clerkClient();
const clerkResponse = await client.users.getUserOauthAccessToken(
userId,
provider
);
const accessToken = clerkResponse.data[0]?.token || "";
if (!accessToken) {
return NextResponse.json(
{ message: "Access token not found" },
{ status: 401 }
);
}
const UsageUrl = "https://oauth.joinares.com/v1/partner/usage";
const ARESResponse = await fetch(UsageUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id,
usage,
credits,
}),
});
if (!ARESResponse.ok) {
return NextResponse.json(
{ error: `ARES API error: ${ARESResponse.status}` },
{ status: ARESResponse.status }
);
}
const ARESData = await ARESResponse.json();
return NextResponse.json(ARESData);
}GET Method (Access User Information)
Calling GET Method
GET Response
Step 2: Track user's usage in your app using the API
POST Method (Logs and Tracks User's Usage to Earn Credits)
Calling POST Method
POST Response
Last updated