Hey sejalapeno,
I can happily tell you I got basic functionality working.
Here is working code of how to display user information from Spotify:
import SpotifyProfile from "./components/SpotifyProfile";
export default function HomePage() {
return (
<main>
<h1>Welcome to Your Spotify Profile</h1>
<SpotifyProfile />
</main>
);
}
import "./globals.css";
import type { Metadata } from "next";
import { ClerkProvider, SignInButton, UserButton } from "@clerk/nextjs";
export const metadata: Metadata = {
title: "Spotify Profile",
description: "View your Spotify profile",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ClerkProvider>
<div className="app-container">
<header>
<nav>
{}
<SignInButton />
<UserButton afterSignOutUrl="/" />
</nav>
</header>
<main>{children}</main>
</div>
</ClerkProvider>
</body>
</html>
);
}
"use client";
import { useEffect, useState } from "react";
import { useAuth } from "@clerk/nextjs";
const SpotifyProfile = () => {
const { isSignedIn } = useAuth();
const [profile, setProfile] = useState<any>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchSpotifyProfile = async () => {
try {
const response = await fetch("/api/spotify");
const data = await response.json();
if (response.ok) {
setProfile(data.message);
} else {
setError(data.message || "Failed to fetch Spotify profile");
}
} catch (err) {
setError("An error occurred while fetching Spotify profile");
}
};
if (isSignedIn) {
fetchSpotifyProfile();
}
}, [isSignedIn]);
if (!isSignedIn) {
return <div>Please sign in to view your Spotify profile.</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
if (!profile) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Spotify Profile</h1>
<p>Name: {profile.display_name}</p>
<p>Email: {profile.email}</p>
{profile.images && profile.images.length > 0 && (
<img src={profile.images[0]?.url} alt="Profile" width={100} />
)}
</div>
);
};
export default SpotifyProfile;
import { auth, clerkClient } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
export async function GET() {
const { userId } = auth();
if (!userId) {
return NextResponse.json({ message: "User not found" }, { status: 401 });
}
try {
const provider = "spotify";
const clerkResponse = await clerkClient().users.getUserOauthAccessToken(
userId,
provider
);
console.log("Clerk Response:", clerkResponse);
const accessToken = clerkResponse.data[0]?.token;
if (!accessToken) {
return NextResponse.json(
{ message: "Access token is undefined" },
{ status: 500 }
);
}
const spotifyUrl = "https://api.spotify.com/v1/me";
const spotifyResponse = await fetch(spotifyUrl, {
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
console.log("Spotify Response Status:", spotifyResponse.status);
if (!spotifyResponse.ok) {
const errorData = await spotifyResponse.json();
console.error("Spotify API Error:", errorData);
return NextResponse.json(
{ message: "Failed to fetch Spotify data", error: errorData },
{ status: spotifyResponse.status }
);
}
const spotifyData = await spotifyResponse.json();
console.log("Spotify Data:", spotifyData);
return NextResponse.json({ message: spotifyData });
} catch (error) {
console.error("Error fetching Spotify data:", error);
return NextResponse.json(
{ message: "Internal Server Error", error: error.message },
{ status: 500 }
);
}
}
I hope this code helps you on how to get an access token from Clerk.
Page used as reference: Social connections (OAuth)
Scopes used: user-read-email, user-read-private
P.S. I could have rewritten this code using Clerk's build in hide and show elements when (not) signed in. This was only the quickest way for now.
XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.