Build a Simple Next.js Cryptocurrency Price Tracker

In the fast-paced world of cryptocurrency, staying informed about price fluctuations is crucial. Whether you’re a seasoned trader or just starting to explore the digital asset market, having a real-time price tracker at your fingertips can provide a significant advantage. This article will guide you through building a simple yet effective cryptocurrency price tracker using Next.js, a powerful React framework for building web applications. We’ll cover everything from setting up your development environment to fetching data from a cryptocurrency API and displaying it in a user-friendly interface. This project is ideal for beginners and intermediate developers looking to enhance their Next.js skills and gain practical experience with API integration and data visualization.

Why Build a Cryptocurrency Price Tracker?

Cryptocurrency prices are notoriously volatile. They can change dramatically within minutes, making it essential to have access to up-to-date information. A price tracker allows you to:

  • Monitor Prices in Real-Time: Stay informed about the latest prices of your favorite cryptocurrencies.
  • Make Informed Decisions: Base your trading or investment decisions on the most current market data.
  • Learn and Experiment: This project is a great way to learn about API integration, data fetching, and front-end development.
  • Personalize Your Experience: Customize the tracker to show only the cryptocurrencies you’re interested in.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  • Node.js and npm (or yarn): You’ll need Node.js and npm (Node Package Manager) or yarn to manage project dependencies. You can download them from the official Node.js website.
  • A Code Editor: A code editor like Visual Studio Code, Sublime Text, or Atom will be helpful for writing and editing code.
  • Basic Knowledge of JavaScript and React: Familiarity with JavaScript and the basics of React is recommended. While this tutorial provides step-by-step instructions, understanding these concepts will make the process smoother.

Setting Up Your Next.js Project

Let’s start by creating a new Next.js project. Open your terminal and run the following command:

npx create-next-app crypto-tracker

This command will create a new Next.js project named “crypto-tracker.” Navigate into the project directory:

cd crypto-tracker

Now, start the development server:

npm run dev

This will start the development server, and you should be able to view your application at http://localhost:3000. You’ll see the default Next.js welcome page.

Installing Dependencies

For this project, we’ll need to install a library to help us fetch data from the cryptocurrency API. We’ll use the ‘axios’ library for making HTTP requests. Install it using npm or yarn:

npm install axios

or

yarn add axios

Choosing a Cryptocurrency API

There are several cryptocurrency APIs available. For this tutorial, we’ll use the CoinGecko API, which offers a free tier with a generous rate limit. You can sign up for a free API key at CoinGecko API. However, for this project, an API key is not strictly required as we will be using public endpoints. Other options include CoinMarketCap and CryptoCompare. Make sure to review the API documentation for the specific API you choose to understand how to fetch data.

Fetching Cryptocurrency Data

Now, let’s write the code to fetch cryptocurrency data. We’ll modify the `pages/index.js` file, which is the main page of our application.

First, import the `useState` and `useEffect` hooks from React and `axios`:

import { useState, useEffect } from 'react';
import axios from 'axios';

Next, define a state variable to hold the cryptocurrency data:

const [cryptoData, setCryptoData] = useState([]);

We’ll use the `useEffect` hook to fetch data when the component mounts. Inside the `useEffect` hook, we’ll make a request to the CoinGecko API. Replace the placeholder URL with the actual endpoint for getting the prices of cryptocurrencies. For example, to get the prices of the top 10 cryptocurrencies, you can use the following endpoint:

https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false

Here’s the complete code for fetching and displaying the data:

import { useState, useEffect } from 'react';
import axios from 'axios';

function HomePage() {
  const [cryptoData, setCryptoData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false');
        setCryptoData(response.data);
        setLoading(false);
      } catch (err) {
        setError(err);
        setLoading(false);
        console.error('Error fetching data:', err);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  return (
    <div>
      <h1>Cryptocurrency Prices</h1>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Symbol</th>
            <th>Price (USD)</th>
            <th>Market Cap (USD)</th>
          </tr>
        </thead>
        <tbody>
          {cryptoData.map(crypto => (
            <tr>
              <td>{crypto.name}</td>
              <td>{crypto.symbol.toUpperCase()}</td>
              <td>${crypto.current_price.toLocaleString()}</td>
              <td>${crypto.market_cap.toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default HomePage;

Let’s break down this code:

  • We import `useState` and `useEffect` from React and `axios` for making API requests.
  • `cryptoData` stores the fetched cryptocurrency data, initialized as an empty array.
  • `loading` is a boolean state variable to indicate whether the data is being fetched.
  • `error` is used to store any errors that occur during the data fetching process.
  • The `useEffect` hook runs once when the component mounts (the empty dependency array `[]`).
  • Inside `useEffect`, the `fetchData` function uses `axios.get()` to fetch data from the CoinGecko API. The API endpoint is specified in the URL.
  • The fetched data is then set to the `cryptoData` state using `setCryptoData()`.
  • We set `loading` to `false` after the data is fetched or an error occurs.
  • If there is an error, the `error` state is updated, and the error is logged to the console.
  • The component renders a “Loading…” message while data is being fetched.
  • If an error occurs, an error message is displayed.
  • The component renders the cryptocurrency data in a table. Each row displays the name, symbol, and current price of a cryptocurrency.

Styling the Cryptocurrency Tracker

To make the price tracker look more visually appealing, let’s add some basic styling. You can add CSS directly to your `index.js` file or create a separate CSS file and import it. Here’s an example of how to add some basic styles directly in the component:

import { useState, useEffect } from 'react';
import axios from 'axios';

function HomePage() {
  const [cryptoData, setCryptoData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false');
        setCryptoData(response.data);
        setLoading(false);
      } catch (err) {
        setError(err);
        setLoading(false);
        console.error('Error fetching data:', err);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  return (
    <div style="{{">
      <h1 style="{{">Cryptocurrency Prices</h1>
      <table style="{{">
        <thead>
          <tr style="{{">
            <th style="{{">Name</th>
            <th style="{{">Symbol</th>
            <th style="{{">Price (USD)</th>
            <th style="{{">Market Cap (USD)</th>
          </tr>
        </thead>
        <tbody>
          {cryptoData.map(crypto => (
            <tr style="{{">
              <td style="{{">{crypto.name}</td>
              <td style="{{">{crypto.symbol.toUpperCase()}</td>
              <td style="{{">${crypto.current_price.toLocaleString()}</td>
              <td style="{{">${crypto.market_cap.toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default HomePage;

This code adds basic styling to the table, including:

  • A sans-serif font and padding for the main container.
  • Centered heading with some margin.
  • Table with a 100% width and collapsed borders.
  • Header row with a light gray background.
  • Padding and borders for table cells.
  • Borders for each row.

Feel free to customize the styles to match your preferences.

Handling Errors

It’s important to handle errors gracefully. In the code above, we’ve included error handling using a `try…catch` block. If an error occurs during the API request, the error message is displayed to the user. You can improve error handling by:

  • Displaying More Informative Error Messages: Instead of just displaying the error message, you can provide more context, such as “Failed to fetch cryptocurrency data. Please check your internet connection.”
  • Logging Errors: Log errors to the console or a logging service for debugging purposes.
  • Retrying Failed Requests: Implement a retry mechanism to attempt the API request again if it fails initially (with a delay to avoid overwhelming the API).
  • Implementing Error Boundaries: Use React error boundaries to gracefully handle errors that occur during rendering.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to fix them:

  • Incorrect API Endpoint: Double-check the API endpoint URL. Make sure it’s correct and that you’re using the correct parameters. Refer to the API documentation.
  • CORS Errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, it means the API server doesn’t allow requests from your domain. You might need to use a proxy server or configure CORS on the API server (if you have control over it). For development, you can often use a browser extension to disable CORS temporarily.
  • Rate Limiting: APIs often have rate limits. If you exceed the rate limit, you’ll receive an error. Implement a mechanism to handle rate limits, such as delaying requests or using a different API tier.
  • Incorrect Data Parsing: Ensure you’re correctly parsing the data returned by the API. Inspect the API response to understand the structure of the data and access the correct fields.
  • Not Handling Loading States: Always show a loading indicator while fetching data. This provides a better user experience.
  • Unnecessary Re-renders: Optimize your component to prevent unnecessary re-renders. Use `React.memo` or `useMemo` to memoize components or values that don’t need to be re-rendered on every update.

Enhancements and Next Steps

Once you’ve built the basic price tracker, you can add several enhancements:

  • Add a Search Feature: Allow users to search for specific cryptocurrencies.
  • Implement Currency Conversion: Allow users to convert prices to different currencies.
  • Display Historical Data: Show historical price charts using a charting library like Chart.js or Recharts.
  • Add User Authentication: Allow users to create accounts and save their favorite cryptocurrencies.
  • Implement Real-Time Updates: Use WebSockets or Server-Sent Events (SSE) to receive real-time price updates.
  • Add Responsiveness: Ensure your tracker looks good on different screen sizes using responsive design techniques.
  • Improve UI/UX: Use a UI library like Material UI or Ant Design to create a more polished user interface.

Summary / Key Takeaways

Building a cryptocurrency price tracker with Next.js is a practical project that can enhance your skills in web development, API integration, and data visualization. By following the steps outlined in this tutorial, you can create a functional price tracker that displays real-time cryptocurrency data. Remember to choose a reliable API, handle errors gracefully, and consider adding enhancements to improve the user experience. This project provides a solid foundation for further exploration in the world of cryptocurrency and web development. You’ve learned how to set up a Next.js project, fetch data from an API, display that data in a user-friendly format, and implement basic styling. You’ve also learned about error handling and common pitfalls to avoid. With this knowledge, you are well-equipped to build more sophisticated web applications that interact with external APIs. Continuous learning and experimentation are key to mastering Next.js and web development in general. Keep exploring, keep building, and stay updated with the ever-evolving world of technology.