Next.js 12 + Spotify API beginner tutorial
Table of Contents
Introduction
In this tutorial, we will set up a Next.js project that uses the Spotify API to curate music recommendations. Throughout the process, we will explore the structure of a Next.js application, learn about data fetching methods, and implement dynamic routing. This guide is aimed at beginners and will help you understand how to create an accessible and scalable web application using Next.js.
Step 1: Set Up Your Next.js Project
- Open your terminal.
- Create a new Next.js project by running:
npx create-next-app music-recommendations
- Navigate into your project directory:
cd music-recommendations
Step 2: Explore the Next.js Folder Structure
Next.js organizes your project into specific directories:
- pages: Contains your application's pages.
- api: For serverless functions.
- public: Static files such as images.
- styles: CSS files for styling your application.
Step 3: Create a Custom Document
- Create a file named
_document.js
in thepages
directory to add alang
attribute to the HTML tag. - Example code:
import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> {/* Add any custom head elements here */} </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
Step 4: Configure Path Aliases
- Create a
jsconfig.json
file in the root of your project to simplify import statements:{ "compilerOptions": { "baseUrl": "." }, "include": ["./pages/**/*", "./components/**/*"] }
Step 5: Edit the Home Page
- Open
pages/index.js
and modify it to set up your home page. - Use the Next.js
Head
component to manage the document head:import Head from 'next/head'; export default function Home() { return ( <div> <Head> <title>Music Recommendations</title> </Head> <h1>Welcome to Music Recommendations</h1> </div> ); }
Step 6: Data Fetching with getStaticProps
- Use
getStaticProps
to fetch data from the Spotify API at build time. - Example code:
export async function getStaticProps() { const res = await fetch('https://api.spotify.com/v1/genres'); const data = await res.json(); return { props: { genres: data.genres } }; }
Step 7: Dynamic Routing with getStaticPaths
- Implement
getStaticPaths
to generate dynamic routes based on Spotify data. - Example code:
export async function getStaticPaths() { const res = await fetch('https://api.spotify.com/v1/albums'); const data = await res.json(); const paths = data.items.map(item => ({ params: { id: item.id.toString() } })); return { paths, fallback: false }; }
Step 8: Fetching Track Recommendations
- Use dynamic route parameters to fetch specific track recommendations.
- Example code:
export async function getStaticProps({ params }) { const res = await fetch(`https://api.spotify.com/v1/albums/${params.id}`); const data = await res.json(); return { props: { track: data } }; }
Step 9: Create a React Component for Rendering
- Create a component to display Spotify track information.
- Example structure:
const TrackInfo = ({ track }) => { return ( <div> <h2>{track.name}</h2> <img src={track.album.images[0].url} alt={track.name} /> </div> ); };
Step 10: Optimize Images with Next Image
- Use the
Next Image
component to optimize images for better performance. - Example usage:
import Image from 'next/image'; <Image src={track.album.images[0].url} alt={track.name} width={500} height={500} layout="responsive" />
Conclusion
In this tutorial, we set up a Next.js application integrated with the Spotify API, covering project structure, data fetching, dynamic routing, and image optimization. You can further enhance your project by implementing Incremental Static Regeneration (ISR) for real-time data updates. Explore the GitHub repository for the complete code and continue developing your skills in Next.js!