Next.js Functions

 

Building a Music Streaming App with NEXT.js and Spotify API

In today’s digital age, music streaming apps have become an integral part of our lives. They provide a convenient way to access and enjoy music from a vast library of songs. If you’re an aspiring web developer looking to create your music streaming app, you’re in the right place. In this comprehensive guide, we will walk you through the process of building a music streaming app using NEXT.js and the Spotify API.

Building a Music Streaming App with NEXT.js and Spotify API

1. Prerequisites

Before we dive into the development process, make sure you have the following prerequisites in place:

1.1. Node.js and npm

Ensure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official Node.js website (https://nodejs.org/).

To check if you have Node.js and npm installed, open your terminal and run the following commands:

bash
node -v
npm -v

These commands should display the installed Node.js and npm versions, respectively.

1.2. Spotify Developer Account

You’ll need a Spotify Developer Account to access the Spotify API. If you don’t have one, you can sign up at the Spotify Developer Dashboard (https://developer.spotify.com/dashboard/).

Once you have your Spotify Developer Account, create a new Spotify App to obtain your API credentials, including the Client ID and Client Secret.

1.3. Basic Knowledge of NEXT.js

Familiarity with NEXT.js, a popular React framework, will be helpful. If you’re new to NEXT.js, you can start with their official documentation (https://nextjs.org/docs/getting-started/introduction).

Now that you have the prerequisites in place, let’s start building our music streaming app step by step.

Step 1: Setting Up the Project

First, let’s create a new NEXT.js project and set up the necessary dependencies. Open your terminal and run the following commands:

bash
npx create-next-app music-streaming-app
cd music-streaming-app

This will create a new NEXT.js project in a directory named music-streaming-app and navigate you to the project folder.

Step 2: Installing Dependencies

To interact with the Spotify API and manage user authentication, we’ll need some npm packages. Install the required packages by running the following commands:

bash
npm install axios dotenv next-auth spotify-web-api-node

Here’s what each package does:

  • axios: A popular HTTP client for making API requests.
  • dotenv: A module for loading environment variables from a .env file.
  • next-auth: A library for authentication in NEXT.js applications.
  • spotify-web-api-node: The official Spotify API wrapper for Node.js.

Step 3: Setting Up Environment Variables

We’ll use environment variables to securely store our Spotify API credentials. Create a .env.local file in the root of your project and add the following variables:

env
SPOTIFY_CLIENT_ID=your-client-id
SPOTIFY_CLIENT_SECRET=your-client-secret
SPOTIFY_REDIRECT_URI=http://localhost:3000/api/auth/callback/spotify

Replace your-client-id and your-client-secret with the credentials you obtained from the Spotify Developer Dashboard.

Step 4: Creating Spotify API Functions

In this step, we’ll create functions to interact with the Spotify API using the spotify-web-api-node package. Create a new file spotify.js inside the lib directory and add the following code:

javascript
import SpotifyWebApi from 'spotify-web-api-node';

const spotifyApi = new SpotifyWebApi({
  clientId: process.env.SPOTIFY_CLIENT_ID,
  clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
  redirectUri: process.env.SPOTIFY_REDIRECT_URI,
});

export default spotifyApi;

This code sets up our Spotify API client with the credentials from our environment variables.

Step 5: User Authentication

We’ll use next-auth to handle user authentication. Create a pages/api/auth/[…nextauth].js file in your project directory and add the following code:

javascript
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import spotifyApi from '../../../lib/spotify';

export default NextAuth({
  providers: [
    Providers.Spotify({
      clientId: process.env.SPOTIFY_CLIENT_ID,
      clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
      scope: 'user-library-read user-read-playback-state user-read-currently-playing',
    }),
  ],
  callbacks: {
    async signIn(user, account, profile) {
      if (account.provider === 'spotify') {
        const accessToken = account.accessToken;
        spotifyApi.setAccessToken(accessToken);
      }
      return true;
    },
  },
  pages: {
    signIn: '/auth/signin',
    signOut: '/auth/signout',
    error: '/auth/error',
    verifyRequest: '/auth/verify-request',
    newUser: null,
  },
});

This code configures the Spotify provider for authentication and sets up the Spotify API access token when a user signs in.

Step 6: Creating the User Interface

Now, let’s create the user interface for our music streaming app. In the pages directory, create a new file index.js with the following code:

jsx
import { useSession, signOut } from 'next-auth/react';

function Home() {
  const { data: session } = useSession();

  return (
    <div>
      {session ? (
        <>
          <h1>Welcome to the Music Streaming App</h1>
          <p>Hello, {session.user.name}!</p>
          <button onClick={() => signOut()}>Sign Out</button>
        </>
      ) : (
        <p>Please sign in to use the app.</p>
      )}
    </div>
  );
}

export default Home;

This code displays a welcome message and a sign-out button if the user is signed in. Otherwise, it prompts the user to sign in.

Step 7: Building the Music Player

Now comes the exciting part—building the music player. In the pages directory, create a new file player.js with the following code:

jsx
import { useSession, signIn } from 'next-auth/react';
import spotifyApi from '../lib/spotify';

function Player({ tracks }) {
  const { data: session } = useSession();

  const playTrack = async (trackUri) => {
    if (!session) {
      await signIn('spotify');
    }

    try {
      await spotifyApi.play({
        uris: [trackUri],
      });
    } catch (error) {
      console.error('Error playing track:', error.message);
    }
  };

  return (
    <div>
      <h1>Music Player</h1>
      {tracks.map((track) => (
        <div key={track.uri}>
          <p>{track.name}</p>
          <button onClick={() => playTrack(track.uri)}>Play</button>
        </div>
      ))}
    </div>
  );
}

export default Player;

This code sets up a music player interface and allows users to play tracks by clicking the “Play” button. If the user is not signed in, it prompts them to sign in via Spotify.

Step 8: Fetching User’s Saved Tracks

To display the user’s saved tracks in the music player, we need to fetch this data from the Spotify API. Add the following function to the spotify.js file:

javascript
export async function getSavedTracks() {
  try {
    const response = await spotifyApi.getMySavedTracks({
      limit: 10, // Adjust the limit as needed
    });
    const tracks = response.body.items.map((item) => item.track);
    return tracks;
  } catch (error) {
    console.error('Error fetching saved tracks:', error.message);
    return [];
  }
}

Now, modify the player.js file to fetch and display the user’s saved tracks:

jsx
import { useSession, signIn } from 'next-auth/react';
import { getSavedTracks } from '../lib/spotify';

function Player() {
  const { data: session } = useSession();
  const [tracks, setTracks] = useState([]);

  useEffect(() => {
    async function fetchSavedTracks() {
      if (session) {
        const savedTracks = await getSavedTracks();
        setTracks(savedTracks);
      }
    }

    fetchSavedTracks();
  }, [session]);

  // ... rest of the code

  return (
    <div>
      <h1>Music Player</h1>
      {tracks.map((track) => (
        <div key={track.uri}>
          <p>{track.name}</p>
          <button onClick={() => playTrack(track.uri)}>Play</button>
        </div>
      ))}
    </div>
  );
}

export default Player;

This code fetches the user’s saved tracks when they are signed in and displays them in the music player.

Step 9: Styling Your App

Aesthetics matter in a music streaming app. You can style your app using CSS, a CSS framework like Tailwind CSS, or a UI library like Material-UI. Customizing the styling is beyond the scope of this tutorial, but feel free to make your app look as appealing as you want.

Step 10: Testing and Deployment

Before deploying your music streaming app, it’s essential to thoroughly test it. Ensure that the authentication, music player functionality, and user experience work seamlessly.

For deployment, you can choose a hosting platform like Vercel, Netlify, or AWS Amplify that supports NEXT.js applications. Follow the deployment instructions provided by your chosen platform to make your app accessible to users worldwide.

Conclusion

Congratulations! You’ve successfully built a music streaming app using NEXT.js and the Spotify API. Your app allows users to authenticate with their Spotify accounts, access their saved tracks, and play music seamlessly. Remember that you can expand and enhance your app by adding features like playlists, searching for songs, and more.

This project provides a solid foundation for creating your music streaming platform. Explore the Spotify API documentation to discover more capabilities and possibilities to take your app to the next level. Happy coding, and enjoy the music!

In this blog post, we’ve walked through the process of building a music streaming app using NEXT.js and the Spotify API. We covered the essential steps, from setting up the project and handling user authentication to creating the user interface and fetching saved tracks. Now, you have the knowledge and tools to start building your music streaming app from scratch. Get creative, add more features, and make your app stand out in the world of music streaming.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Accomplished Senior Software Engineer with Next.js expertise. 8 years of total experience. Proficient in React, Python, Node.js, MySQL, React Hooks, and more.